Search code examples
javascriptangularjsangularjs-scope

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?


Solution

  • 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.