我正在看一些使用Angular构建的示例应用程序.我正在寻找模型的创建/存储位置.我注意到有时模型存储在一个普通的javascript文件中,如下所示:
customer.js:
function customer(){
this.firstName;
this.lastName;
}
customer.prototype.getFullName = function(){
return this.firstName + ' ' + this.lastName;
}
Run Code Online (Sandbox Code Playgroud)
我还看到了工厂的使用:
customerFactory.js:
app.factory("customer", function(){
return function(){
this.firstName;
this.lastName;
this.getFullName = function(){
return this.firstName + ' ' + this.lastName;
};
};
});
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,你在哪里存储模型以及为什么?这个人比其他人有更多优势吗?
我特别喜欢第二种方法,即使用工厂来创建模型。
myApp.factory('Models', [function() {
return {
Customer: (function() {
var cls = function(obj) {
this.firstName = obj && obj.firstName || null;
this.lastName = obj && obj.lastName || null;
}
cls.prototype.getFullName = function() {
return this.firstName + ' ' + this.lastName;
};
return cls;
})(),
Order: (function() {
var cls = function(obj) {
this.id = obj.id || null;
this.amount = obj.amount || null;
}
/* methods */
return cls;
})()
}
}]);
Run Code Online (Sandbox Code Playgroud)
这样,您只需在控制器中注入一个依赖项,并且该对象是一个定义的模型就变得明确了。
myApp.controller('myCtrl', ['$scope', 'Model', function($scope, Model) {
$scope.customer = new Model.Customer({
firstName: "Beterraba"
, lastName: "Abacate"
});
}]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
242 次 |
| 最近记录: |