为什么$ watch没有开火

时间:2014-12-12 10:19:14

标签: angularjs

我正在尝试使用$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

3 个答案:

答案 0 :(得分:3)

它没有触发,因为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在{strong>相同摘要循环执行中注册,string变量初始化。

答案 1 :(得分:2)

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

答案 2 :(得分:2)

你的$ 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>
相关问题