我有一个指令,应该在服务变量发生变化时调用函数。
以下代码在指令中:
$rootScope.$watch('movesService.selectedMove', function() {
console.log(movesService.selectedMove);
if (movesService.selectedMove === "Punch") {
vm.pushToFightLog('Select Target');
}
if (movesService.selectedMove === "Fury") {
//Action
}
if (movesService.selectedMove === "Fortify") {
//Action
}
if (movesService.selectedMove === "Parry") {
//Action
}
}, true);
服务:
angular
.module('outerZone')
.service('movesService', movesService);
function movesService() {
var vm = this;
vm.selectedMove = "Punch";
}
事情是,当第一次调用$ watch时,它能够读取变量并将其记录到控制台,但即使在此之后更改变量,它也不会触发该函数。
我非常确信$ rootScope已正确注入,但这里的代码只是为了仔细检查。
angular
.module('outerZone')
.directive('fightDisplay', fightDisplay);
fightDisplay.$inject = ["alliesService", "enemiesService", "fightQueueService", "$timeout", "movesService", "$rootScope"];
function fightDisplay(alliesService, enemiesService, fightQueueService, $timeout, movesService, $rootScope) {
答案 0 :(得分:0)
使用您提供的plunker,我在手表功能中做了一些更改,如下所示。
exec Table_CHANGES('value2')
如果我们想要严格检查,请更改$scope.$watch('test', function() { //scope variable should be watched like this
$scope.watchCount++
});//removed true for strict checking (===) as $scope.test is initalised as String 'Hello'
和
$scope.test =0