Search code examples
javascriptangularjsangularjs-watch

$watchcollection doesn't work on model property


I'm using $watchcollection for to observe the my model upon changes. i initialized my model like this

$scope.feature = {
        additional: [],
        collision: 0,
        baseTotal: 0
    }

i use $watchcollection to check model changes

$scope.$watchCollection('feature', function (val) {
    var addtional = 0;
    angular.forEach(val.additional, function (e, t) {
        addtional += parseFloat(e.value.toFixed(2));
    });
},true);

Problem is, this not getting fired when only update feature.additional.
Does anybody have any work around or please let me know if something is wrong.


Solution

  • Try using

    $scope.$watch('feature', function (newVal, oldVal) {
      var addtional = 0;
      angular.forEach(newVal.additional, function (e, t) {
        addtional += parseFloat(e.value.toFixed(2));
      });
    }, true);