Angularjs $watch函数的问题
我不是很确定这个问题,但似乎有时当我为一个函数激活$watch时,它就不起作用了。 例如,我有这个简单的服务Angularjs $watch函数的问题,angularjs,angularjs-scope,Angularjs,Angularjs Scope,我不是很确定这个问题,但似乎有时当我为一个函数激活$watch时,它就不起作用了。 例如,我有这个简单的服务 angular.module('sp-app').factory('mediaSources', function() { var storages = []; return { addStorage: function(storage) { storages.push(storage); }, g
angular.module('sp-app').factory('mediaSources', function() {
var storages = [];
return {
addStorage: function(storage) {
storages.push(storage);
},
getStorages: function() {
return storages;
}
}
});
当我观察getStorage方法以更新视图时,它不会调用change回调,或者只在初始化阶段调用
$scope.$watch(function($scope) {
return mediaSources.getStorages();
}, function() {
console.log('call')
});
我只能通过观察返回数组的长度属性来跟踪更改
返回mediaSources.getStorages().length代码>
我想知道,因为我在我的应用程序中的其他地方写了类似的think,它工作得很好。如果我解释了您试图做的事情,您不需要在这样的事情上设置手表,您可以使用这样的工厂:
angular.module('app').factory('mediaSources', function(){
var storages = {};
storages.list = [];
storages.add = function(message){
storages.list.push(message);
};
return storages;
});
然后在您想要接收/更新数据的控制器中,例如
$scope.myControllerVar = mediaSources.list;
不需要监视它,它应该为您更新。您必须将watcher设置为第三个参数:
$scope.$watch(function($scope) {
return mediaSources.getStorages();
}, function() {
console.log('call');
}, true);
您如何解释它有时对其他组件有效?