【发布时间】:2014-01-07 04:22:05
【问题描述】:
我正在尝试从控制器观察服务的变化。我在stackoverflow上尝试了基于许多qns的各种事情,但我一直无法使其工作。
html:
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<div ng-click="setFTag()">Click Me</div>
</div>
</div>
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);
});
如何让手表在 Controller 中触发?
【问题讨论】:
-
在问题here 中查看我的答案。
watch函数中的语法不是您想要的,但它仍然是有效的角度语法,这就是您没有收到日志错误的原因。