【问题标题】:Why is $watch not firing为什么 $watch 没有触发
【发布时间】:2014-12-12 10:19:14
【问题描述】:

我正在尝试使用$watch,但它并没有在我期望的时候触发。

为什么当$scope.string 改变时下面的代码没有触发?

$scope.string = 'Hello.';
$scope.timesChanged = 0;

$scope.$watch('string', function (newValue) {
    $scope.timesChanged =+ 1;
});

$scope.string = 'How are you';
$scope.string = 'doing today?';

这是fiddle

【问题讨论】:

标签: angularjs


【解决方案1】:

它不会触发,因为 Angular 无法知道您在声明字符串后立即更改了它。在这种情况下,没有什么会触发新的摘要循环,因此 $watch 不会触发。基本上这和你写的一样

$scope.string = 'Hello.';
$scope.string = 'How are you';
$scope.string = 'doing today?';

$scope.timesChanged = 0;

$scope.$watch('string', function (newValue) {
    $scope.timesChanged =+ 1; // you probably want += 1 here.
});

Watcher 在 same 摘要循环执行中注册,string 变量初始化。

【讨论】:

  • 好吧,而且=+ 不是+= 所以即使他的测试也不正确。
【解决方案2】:

我认为问题在于您的手表不会被触发,因为范围的更改发生在与手表创建相同的范围更新中。您正在初始化控制器,以便在 angular 可以检查任何内容之前应用所有内容。手表未激活。

【讨论】:

    【解决方案3】:

    你的 $watch 没问题,你只是期待错误的结果。

    $watch 函数设置为仅在控制器首次编译后才进行监视,然后才起作用。

    我更新了你的小提琴,所以你可以看到它的实际效果:

    http://jsfiddle.net/S9rV2/27/

    var app = angular.module('myApp', []);
    
    function MyCtrl($scope) {
    
        $scope.string = 'Hello.';
        $scope.timesChanged = 0;
    
        $scope.$watch('string', function (newValue) {
            $scope.timesChanged++;
        });
    
        $scope.string = 'How are you';
        $scope.string = 'doing today?';
    
    }
    <div ng-controller="MyCtrl">{{ timesChanged }}
        <br/>
        <input type="text" ng-model="string"></input>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-17
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-23
      • 2021-06-21
      相关资源
      最近更新 更多