AngularJS : Basic $watch not working

后端 未结 3 1500
鱼传尺愫
鱼传尺愫 2020-12-15 06:13

I\'m attempting to set up a watch in AngularJS and I\'m clearly doing something wrong, but I can\'t quite figure it out. The watch is firing on the immediate page load, but

相关标签:
3条回答
  • 2020-12-15 06:45

    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);
    
    0 讨论(0)
  • 2020-12-15 07:10

    You can use without $interval and $timeout

    $scope.$watch(function() {
                return variableToWatch;
            }, function(newVal, oldVal) {
                if (newVal !== oldVal) {
                    //custom logic goes here......
                }
            }, true);
    
    0 讨论(0)
  • 2020-12-15 07:10

    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">
    
    0 讨论(0)
提交回复
热议问题