我有一个工厂函数,它有一些数据和一些操作它的函数。该数据在应用程序中被多次使用,在某些时候,数据在页面上,然后在一个模态中打开--操作模态中的数据,更改后台页面中的数据。创建数据的独立实例的最“角度方式”是什么?
更新:
工厂:
factory('filterFactory', [function () {
return {
getGroups: function(term){
// TODO: get terms groups with $http
if(term){
// get terms
}
else {
return this.terms;
}
},
addGroup: function(group){
for (var term in this.terms) {
if(this.terms[term].name === group){
this.terms[term].included = true;
}
}
},
removeGroup: function(group){
for (var term in this.terms) {
if(this.terms[term].name === group){
this.terms[term].included = false;
}
}
},
selectGroup : function(group){
for (var term in this.terms) {
if(this.terms[term].name === group){
this.terms[term].included = true;
} else {
this.terms[term].included = false;
}
}
},
setAll : function(value){
for (var term in this.terms) {
this.terms[term].included = value;
}
},
isCollapsed: true,
terms: {
people: {
included: false,
name: 'person',
},
organizations: {
included: false,
name: 'organization',
},
...
}
};])。
尝试实现:
$scope.newTermMeta.type = filterFactory;
var temp = filterFactory;
$scope.newTermMeta.type = temp.terms;
$scope.newTermMeta.type = filterFactory.getGroups();
var temp = filterFactory;
$scope.newTermMeta.type = temp.terms;
$scope.newTermMeta.type = Object.create(filterFactory.getGroups());注意:上面的实现都没有创建一个孤立的实例。
模板代码:
<div class="modal-body">
<form>
<label>
<h2>{{newTermMeta.name}}</h2>
</label>
<br>
<span>Add your term to relevant term groups:</span>
<br>
<div class="well well-sm col-sm-8">
<button ng-repeat="group in newTermMeta.type" btn-checkbox class="btn btn-sm btn-default margin5" type="button" ng-model="group.included">{{group.name}}</button>
</div>
<br>
<span>Optional:</span>
<br>
<label> Enter a concise (at most one sentence) definition for this term:</label>
<input class="form-control width80p" type="text" ng-model="newTermMeta.definition">
</form>
</div>发布于 2014-03-10 16:07:02
工厂对象是一个共享实例,因此您在该工厂对象中更改的任何内容都会对每个使用它的人进行更改。
工厂是正确的做法,但听起来您想要将它封装在一个不同的范围中。这与角度相当容易,因为所有控制器都有自己的作用域,指令也可以有自己的作用域。假设您在控制器中显示它,您可以这样做:
myapp.controller('OtherCtrl', [ 'MyFactory', '$scope', function(MyFactory,$scope) {
// create a defensive copy of the factory object by creating a new object with the wrapped object as its prototype chain, anything can then access the data but changing the properties change only on $scope.theObject directly
$scope.theObject = Object.create(MyFactory.getTheObject());
// alternatively, copy the relevant properties into our scope, it's protected but you won't be updated when the factory object changes unless you also specify a $watch statement
var obj = MyFactory.getTheObject();
$scope.name = obj.name;
}]);更新:警告
使用Object.create()防御性复制机制时要注意的一点是,它只会使您修改的属性紧张。如果您打算修改一个属性,然后将整个对象提交回服务器,它将无法工作。但是,它对于只读属性或仅序列化修改后的属性非常有用。角将在没有$watch的情况下更新未经修改的属性的值,因为它仍然可以通过原型链检测变化。
演示JSON.stringify和原型链值之间的区别的小提琴是在这里http://jsfiddle.net/XXdqv/
https://stackoverflow.com/questions/22305114
复制相似问题