AngularJS:如何看服务的变量? [英] AngularJS : How to watch service variables?
问题描述
我有一个服务,说:
factory('aService', ['$rootScope', '$resource', function ($rootScope, $resource) {
var service = {
foo: []
};
return service;
}]);
和我想用富
来控制在HTML渲染列表:
And I would like to use foo
to control a list that is rendered in HTML:
<div ng-controller="FooCtrl">
<div ng-repeat="item in foo">{{ item }}</div>
</div>
为了使控制器检测到何时 aService.foo
更新我已经拼凑这种模式在这里我想补充aService到控制器的 $范围
,然后用 $ $范围腕表()
:
In order for the controller to detect when aService.foo
is updated I have cobbled together this pattern where I add aService to the controller's $scope
and then use $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;
}
});
}
这感觉长手,我已经在使用该服务的变量,每个控制器一直在重复它。有没有更好的方式来完成观看共享变量?
This feels long-handed, and I've been repeating it in every controller that uses the service's variables. Is there a better way to accomplish watching shared variables?
推荐答案
您可以随时,如果你想避免 $观看
。
You can always use the good old observer pattern if you want to avoid the tyranny and overhead of $watch
.
在该服务:
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
};
这篇关于AngularJS:如何看服务的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!