我有一个服务,说:
factory('aService',['$rootScope','$resource',function ($rootScope,$resource) { var service = { foo: [] }; return service; }]);
我想使用foo来控制在HTML中呈现的列表:
<div ng-controller="FooCtrl"> <div ng-repeat="item in foo">{{ item }}</div> </div>
为了控制器检测到aService.foo更新我已经拼凑在一起这个模式,我添加一个服务到控制器的$范围,然后使用$ scope。$ watch():
function FooCtrl($scope,aService) { $scope.aService = aService; $scope.foo = aService.foo; $scope.$watch('aService.foo',function (newVal,oldVal,scope) { if(newVal) { scope.foo = newVal; } }); }
这感觉很长久,我已经在使用服务的变量的每个控制器重复它。有没有更好的方法来完成观察共享变量?
如果你想避免$ watch的暴政和开销,你总是可以使用好的旧观察者模式。
原文链接:https://www.f2er.com/angularjs/147496.html在服务:
factory('aService',function() { var observerCallbacks = []; //register an observer this.registerObserverCallback = function(callback){ observerCallbacks.push(callback); }; //call this when you know 'foo' has been changed var notifyObservers = function(){ angular.forEach(observerCallbacks,function(callback){ callback(); }); }; //example of when you may want to notify observers this.foo = someNgResource.query().$then(function(){ notifyObservers(); }); });
并在控制器中:
function FooCtrl($scope,aService){ var updateFoo = function(){ $scope.foo = aService.foo; }; aService.registerObserverCallback(updateFoo); //service now in control of updating foo };