javascriptangularjsangularjs-scopeangularjs-watch

$watch not firing on variables with a dollar ($)


i have a watch for an object. when a property of the object changed, the watch fires, unless the property name starts with a dollar ($).

consider this code:

$scope.data = {};

$scope.$watch('data', function (newValue, oldValue) {
        console.log('fired', newValue);
    }, true);

and the html:

<div>
this will fire the event
<input type="text" ng-model="data.x" />
</div>
<div>
this won't
<input type="text" ng-model="data.$" />
</div>

you can see it for yourself in this fiddle: https://jsfiddle.net/gtrwzsn1/179/

this is very important for me, since I must use a property name with $ for filter purposes.


Solution

  • AngularJs has "$watchCollection" function as a means to observe changes in a collection (i.e. either an Array or an Object).

    $scope.$watchCollection('data', function (newValue, oldValue) {
      console.log('fired', newValue);
    });
    

    Please try above snippet as you want to watch an object. Hope this helps.