问题描述
我有一个从外部来源检索数据的工厂.获得数据后,我立即使用第二个工厂按特定标准对其进行过滤.
I have a factory that is retrieving the data from an external source. As soon as i get the data, i use a second factory to filter it by a certain criteria.
工厂属性被分配给作用域.
The factory property is assigned to scope.
现在,当我在我的工厂中执行此操作时,它不会更新范围:
Now when i do this in my factory, it doesn't update the scope:
factory.foo = [{id:1,name:'foo'}]; // doesn't work
因此第二家工厂的过滤器也不起作用
therefor also the filterin in a second factory doesn't work
factory.foo = Filter.filter(); // doesn't work
虽然这有效:
factory.foo.push({id:1,name:'foo'}); // works
有人知道这是不是有意为之,为什么会这样,以及如何解决?
Does anyone have an idea if this is intended and why it is like this, and how to solve it?
app.factory('Foo',function(Filter) {
var factory = {
foo:[],
getDataForFoo:function() {
factory.foo = Filter.filter(); // doesn't work
//factory.foo = [{id:1,name:'foo'},{id:1,name:'foo'}]; // doesn't work
//factory.foo.push({id:1,name:'foo'}); // works
}
};
return factory;
});
app.factory('Filter',function() {
var factory = {
filter:function() {
var arr = [];
arr.push({id:1,name:'foo'});
return arr;
}
}
return factory;
});
app.controller('MainCtrl', function($scope,Foo) {
$scope.test = 'running';
$scope.foo = Foo.foo;
$scope.click = Foo.getDataForFoo;
});
推荐答案
问题是您的工厂替换了对 Factory.foo
的引用.当你的范围被初始化时,$scope.foo
持有一个对数组的引用(空).当您调用 Foo.getDataForFoo
时,它会在内部更改对 Factory.foo
的引用,但您的作用域仍保留对前一个数组的引用.这就是使用 push
起作用的原因,因为它不会更改数组引用,而是更改数组内容.
The problem is that your factory replace the reference to Factory.foo
. When your scope is initialized, $scope.foo
holds a reference to an array (empty). When you call Foo.getDataForFoo
, it internally changes the reference to Factory.foo
but your scope still hold a reference to the previous array. This is why using push
works as it doesn't change the array reference, but the array content.
有几种方法可以解决这个问题.不考虑所有不同的选项,最简单的方法是将 $scope.foo
包装在一个函数中,返回 Factory.foo
.这样,Angular 将检测摘要循环中的引用更改,并相应地更新视图.
There are a few ways to fix this. Without going in all the different options, the easiest one is to wrap your $scope.foo
in a function, returning Factory.foo
. This way, Angular will detect a reference change in a digest cycle and will update the view accordingly.
app.controller('MainCtrl', function($scope,Foo) {
$scope.test = 'running';
$scope.foo = function() { return Foo.foo };
$scope.click = Foo.getDataForFoo
});
// And in the view (the relevant part)
<ul ng-repeat="elem in foo()">
<li>{{elem.id}} {{elem.name}}</li>
</ul>
<a href="" ng-click="click()">add</a>
这篇关于不使用 push() 时,AngularJS 工厂属性不会在 $scope 中更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!