Angular JS - Scope Watch Not Updating

ぐ巨炮叔叔 提交于 2019-12-11 11:22:54

问题


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?


回答1:


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.




回答2:


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.




回答3:


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;
    }
};


来源:https://stackoverflow.com/questions/23231392/angular-js-scope-watch-not-updating

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