21
AngularJS:如何观察服务变量?
我有服务,说: 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更新,我将这种模式拼凑在一起,在其中我将aService添加到控制器中$scope,然后使用$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; …