首先 - 我是 AngularJS 的新手 ...
我创建了一个工厂类,我想为其创建一些实例,但问题是,当创建我的“Case”类的新实例时,我的其他实例会更改为......我确定它很漂亮很简单,但想不通。
我认为我做一个简单的(通用的)类很聪明
我的工厂类:
.factory('Case', function($q, $http) {
var optionsProto = {
id : null,
reference : "",
fields : []
}
var self = this;
return function Case(options) {
angular.extend(self, optionsProto, options);
return self;
// Updates via. webservice, if posible
this.update = function get(options) {
// not implemented yet
return self;
};
// Saves via. webservice, if posible
this.save = function save() {
// not implemented yet
return self;
};
}
})
我的 Controller :
.controller('CasesCtrl', function($scope, Case) {
$scope.cases = [
new Case({"id": 1}),
new Case({"id": 2}),
new Case({"id": 3}),
];
console.log($scope.cases);
})
控制台输出(如)::
Object {id: 3}
Object {id: 3}
Object {id: 3}
最佳答案
您引用了错误的this
。尝试:
.factory('Case', function($q, $http) {
var optionsProto = {
id : null,
reference : "",
fields : []
};
return function Case(options) {
angular.extend(this, optionsProto, options);
// Updates via. webservice, if posible
this.update = function get(options) {
// not implemented yet
return this;
};
// Saves via. webservice, if posible
this.save = function save() {
// not implemented yet
return this;
};
}
});
如果您想保留 self
变量(以便所有函数都绑定(bind)到 Case 对象),请执行以下操作:
return function Case(options) {
var self = this;
angular.extend(self, optionsProto, options);
// Updates via. webservice, if posible
this.update = function get(options) {
// not implemented yet
return self;
};
// Saves via. webservice, if posible
this.save = function save() {
// not implemented yet
return self;
};
}
另外:请注意,我删除了 return self;
行。这是因为 new
语句总是返回创建的对象,它会中断函数的其余部分。
关于javascript - 具有多个新实例的 AngularJS 工厂类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28909823/