所以我有这个简单的系统用户列表(附有屏幕截图),客户端可以编辑用户或创建新用户,并相应地显示一个新面板。
我正在做的是根据用户操作更新编辑/创建表单的不同字段。但由于我来自 Backbone 背景,我做这样的事情的通常方法是创建一个新 View ,使用指示它是创建模式还是编辑模式的参数初始化它,然后在单击取消/保存时销毁此 View 更改/创建用户。但现在我只是依靠 Angular 事件绑定(bind)来更新相同的表单元素,这是在 Angular 中执行此操作的正确方法吗?
$scope.prepare_form = function (user_id) {
if (user_id) {
// edit mode
var user = filterFilter($scope.users, { id: user_id })[0];
$scope.fdata_create.name = user.name;
$scope.fdata_create.email = user.email;
$scope.fdata_create.role_name = user.role_name;
$scope.fdata_create.id = user.id;
} else {
// create mode
$scope.fdata_create.name = '';
$scope.fdata_create.email = '';
$scope.fdata_create.role_name = '';
$scope.fdata_create.id = '';
}
$scope.form_create_open = true;
}
最佳答案
你应该基于模型而不是形式来思考。您应该使用其同步方法、更新、创建、替换等创建 Teammate 模型。它更干净,这里是来自此 tutorial 的示例摘录
书籍 html 表单。
<div ng-controller="BookController">
<div ng-style="{ backgroundImage: 'url(' + book.getImageUrl(100, 100) + ')' }"></div>
Id: <span ng-bind="book.id"></span>
<br/>
Name:<input type="text" ng-model="book.name" />
<br/>
Author: <input type="text" ng-model="book.author" />
<br/>
Is Available: <span ng-bind="book.isAvailable() ? 'Yes' : 'No' "></span>
<br/>
<button ng-click="book.delete()">Delete</button>
<br/>
<button ng-click="book.update()">Update</button>
</div>
书籍模型定义为工厂。
app.factory('Book', ['$http', function($http) {
function Book(bookData) {
if (bookData) {
this.setData(bookData):
}
// Some other initializations related to book
};
Book.prototype = {
setData: function(bookData) {
angular.extend(this, bookData);
},
load: function(id) {
var scope = this;
$http.get('ourserver/books/' + bookId).success(function(bookData) {
scope.setData(bookData);
});
},
delete: function() {
$http.delete('ourserver/books/' + bookId);
},
update: function() {
$http.put('ourserver/books/' + bookId, this);
},
getImageUrl: function(width, height) {
return 'our/image/service/' + this.book.id + '/' + width + '/' + height;
},
isAvailable: function() {
if (!this.book.stores || this.book.stores.length === 0) {
return false;
}
return this.book.stores.some(function(store) {
return store.quantity > 0;
});
}
};
return Book;
}]);
使用 Book 模型的 Book Controller
app.controller('BookController', ['$scope', 'Book', function($scope, Book) {
$scope.book = new Book();
$scope.book.load(1);
}]);
例如,如果您想更新书籍名称,则无需手动分配新名称,因为书籍的名称实例已绑定(bind)到 ng-model 属性。要更新它只需要从 Book Factory 调用更新函数即可。
$scope.book = new Book();
if(book_id){
$scope.book.load(book_id);
$scope.submit_book = $scope.book.update // submit_book function need to be triggered after submit the form. Here it
}
else{
$scope.submit_book = $scope.book.create // submit_book function need to be triggered after submit the form. Here it will create the book
}
关于angularjs - Angular 拆分组件的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28143335/