简体   繁体   中英

Angular JS - Scope Watch Not Updating

I might be using this wrong, but I have a function that watches a variable and when that variable is changed from the view, the function runs.. but when a sibling function changes that variable the watch doesn't run. Am I coding something wrong?

scope.$watch (settings.number, function(val){
    alert('test');
})
scope.exampleObj = {
    exampleFunc : function(){
        settings.number += 5;
    }
};

so when I call scope.exampleObj.exampleFunc(); shouldn't scope watch get called?

Replace string to a function or use $watchCollection, like this:

Using var:

angular.module('TestApp', [])
    .controller('MainCtrl', function($scope){
        // Object
        var settings = {
            number: 1,
            foobar: 'Hello World'
        };

        $scope.$watch(function(){ return settings.number; }, function(newValue, oldValue){
            console.log('New value detected in settins.number');
        });

        $scope.$watchCollection(function(){ return settings; }, function(newValue, oldValue){
            console.log('New value detected in settings');
        });
    });

Using $scope:

angular.module('TestApp', [])
    .controller('MainCtrl', function($scope){
        // Object
        $scope.settings = {
            number: 1,
            foobar: 'Hello World'
        };

        $scope.$watch('settings.number', function(newValue, oldValue){
            console.log('New value detected in $scope.settings.number');
        });
    });

Example: http://jsfiddle.net/Chofoteddy/2SNFG/

*Note : $watchCollection that is available in AngularJS version 1.1.x and above. It can be really useful if you need to watch multiple values in a array or multiple properties in a object.

The watcher expects the name(ie. string) of a property of inside the scope, not the object itself.

scope.$watch ('settings.number', function(newval,oldval){
   alert('test');
});
  scope.exampleObj = {
  exampleFunc : function(){
      scope.settings.number += 5;
  }
};

I'm assuming the somewhere you declare scope.settings.number first, and that you meant to set scope.settings.number not settings.number as you can only watch variables which are properties of the angular scope .

Though you may be doing the right thing with just settings.number += 5; , I may just be tired.

You need to set the objectEquality to true . so you can compare for object equality using angular.equals instead of comparing for reference equality.

for more infos visit the documentation

scope.$watch (settings.number, function(val){
    alert('test');
},true)
scope.exampleObj = {
    exampleFunc : function(){
        settings.number += 5;
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM