从控制器服务AngularJS触发和观察对象价值变动 [英] AngularJS trigger and watch object value change in service from controller
问题描述
我试图观看从控制器在服务的变化。我试图基于各种事情很多QNS这里计算器,但我一直无法使其工作。
I'm trying to watch for changes in a service from a controller. I tried various things based on many qns here on stackoverflow, but I've been unable to make it work.
HTML
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<div ng-click="setFTag()">Click Me</div>
</div>
</div>
JavaScript的:
javascript:
var myApp = angular.module('myApp',[]);
myApp.service('myService', function() {
this.tags = {
a: true,
b: true
};
this.setFalseTag = function() {
alert("Within myService->setFalseTag");
this.tags.a = false;
this.tags.b = false;
//how do I get the watch in MyCtrl to be triggered?
};
});
myApp.controller('MyCtrl', function($scope, myService) {
$scope.setFTag = function() {
alert("Within MyCtrl->setFTag");
myService.setFalseTag();
};
$scope.$watch(myService.tags, function(newVal, oldVal) {
alert("Inside watch");
console.log(newVal);
console.log(oldVal);
}, true);
});
我如何拿到手表在控制器触发?
How do I get the watch to trigger in the Controller?
推荐答案
试着写 $观看
通过这样的方式:
Try to write $watch
by this way:
myApp.controller('MyCtrl', function($scope, myService) {
$scope.setFTag = function() {
myService.setFalseTag();
};
$scope.$watch(function () {
return myService.tags;
},
function(newVal, oldVal) {
/*...*/
}, true);
});
演示<大骨节病> 小提琴 骨节病>
有时,这样就不会特别是工作,如果服务已经从政党3D更新。
Sometimes this way will not work especially if service has been updated from 3d party.
要使它发挥作用,我们必须的帮助的角度来火消化周期。
To make it work we must help to angular to fire digest cycle.
下面是一个例子:
在服务端的时候,我们要更新标记
值写是这样的:
On service side when we want update tags
value write something like:
if($rootScope.$root.$$phase != '$apply' && $rootScope.$root.$$phase != '$digest'){
$rootScope.$apply(function() {
self.tags = true;
});
}
else {
self.tags = true;
}
这篇关于从控制器服务AngularJS触发和观察对象价值变动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!