簡體   English   中英

AngularJS $ watch行為異常

[英]AngularJS $watch not behaving as expected

我有一條指令,每當服務變量更改時,該指令應調用一個函數。

指令內部包含以下代碼:

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

使用您提供的插頭,我對手表的功能進行了一些更改,如下所示。

$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()的工作原理,請查看此博客

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM