in a directive, $watch fires two times reverting newValue to the original pre $watch firing value

孤人 提交于 2019-12-03 21:35:44

It is because you watching for changes in primitive values (integers) of your $scope.block array.

Try this in controller

 $scope.block = [{value: 3}, {value: 2}, {value: 1}, {value: 0}];

and then in view:

<square ng-repeat="squareValue in block" value="squareValue.value"></square>

(Englsh isn't my first language, so sorry for the short answer)

You should not be using primitive values for watching changes because due to prototypical inheritance in javascript child scope overrites parent scope values .Kindly see very good article which explains all the reasons. https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance

Another answer that might help someone is that you need to check that the newVal has changed, newVal will always be passed in, so you would need check that it is not the same ie:

$scope.$watch('someProperty', function(newVal, oldVal) {
    if (newVal !== oldVal) {
        // do something
    }
});

I found that this solved my issue of $watch listener firing prematurely, regardless of whether the scope property was primitive or not, ie my property was an integer $scope.menuId.

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