AngularJS : Basic $watch not working

我的梦境 提交于 2019-11-28 23:18:13

It's because you update the value without Angular knowing.

You should use the $timeout service instead of setTimeout, and you won't need to worry about that problem.

function testCtrl($scope, $timeout) {
    $scope.hello = 0;

    var t = $timeout( function() { 
        $scope.hello++;
        console.log($scope.hello); 
    }, 5000);

    $scope.$watch('hello', function() { console.log('watch!'); });
}

Or you could call $scope.$apply(); to force angular to recheck the values and call watches if necessary.

var t = setTimeout( function() { 
    $scope.hello++;
    console.log($scope.hello); 
    $scope.$apply();
}, 5000);

You can use without $interval and $timeout

$scope.$watch(function() {
            return variableToWatch;
        }, function(newVal, oldVal) {
            if (newVal !== oldVal) {
                //custom logic goes here......
            }
        }, true);

It can also happen because the div is not registered with the controller. Add a controller to your div as follows and your watch should work:

<div ng-controller="myController">
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!