我在 AngularJS 中发现了奇怪的行为。在我看来像是一个错误,但也许这是合理的。
我有一些值作为属性传递给我的指令。在该指令中,我使用 $scope.$watch
观察参数。事实证明,如果我将 ng-if
放在具有相同参数的指令上,则 $watch
将被错误的旧值触发(旧值==新值)。
我需要知道值何时真正发生变化(以区别于在没有更改的情况下触发 $watch
时的初始运行)。如果这不是一个错误,那么我如何知道旧值是否与我的指令中的当前值不同?
Here is the fiddle to show the problem
HTML 代码:
<div ng-controller="myCtrl">
<select ng-model='myValue'>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<check-change value="myValue"></check-change>
<check-change value="myValue" ng-if="myValue==3"></check-change>
</div>
JS 后端:
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function ($scope) {
$scope.myValue = 1;
});
myApp.directive('checkChange', function () {
return {
restrict: 'E',
template: '<div>{{result}}</div>',
scope: {
value: '='
},
controller: directiveController
};
});
var directiveController = function ($scope) {
$scope.$watch('value', function (newVal, oldVal) {
$scope.result = 'Watch launched, result: ' + (newVal == oldVal);
});
};
最佳答案
这是我从 Angular JS 合作者 Narretz 那里得到的答案:
When the element gets destroyed via ng-if, it's scope and therefore the watcher on it is also destroyed. When the element is rendered again, the watcher is initialized again - which means it's called with the same values, because it triggers the exception.
全线程here
关于javascript - 使用 ng-if 时,$scope.$watch 会以相同的旧值和新值触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32495931/