AngularJS $watch的行为不符合预期

AngularJS $watch not behaving as expected

本文关键字:不符合 watch AngularJS      更新时间:2023-09-26

我有一个指令,当一个服务变量被改变时,它应该调用一个函数。

指令内部的代码如下:

$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) {

使用您提供的plunker,我对watch功能做了如下修改

$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

$scope.$watch('test', function() {
    $scope.watchCount++
  },true);

这是工作柱塞。要了解更多关于$watch()的工作原理,请查看这个博客