见
this jsfiddle;我有两组输入框,其中的范围变量通过ng-model附加.
可以将此系统视为谷歌风格搜索,只需一个搜索框和“高级搜索”.
>当更新单个搜索输入时(在示例中为a),则存在更新相关“高级”输入的功能.我在$scope中实现了这个.$watch(‘a’,…).
>当编辑“高级”搜索输入时,还应更新单个输入(在$scope.$watch(‘b’,…)中实现.
当然,这两个会产生反馈循环 – 更新b,反之亦然,无限制 – 这不好!我希望能够在上面的每个手表的开头发出“暂停其他观察者”命令,然后(在更新其他变量之后)发出“重启观察者”命令,以防止这种情况发生.
有没有办法做到这一点?
最佳答案 我把一个简单的例子放在一起.
<body ng-app="app" ng-controller="myTestCntrl">
<input type="button" ng-click="increaseCounter()" value="Click me" /> clicked: {{counter}z} times<br/>
<input type="button" ng-click="pauseWatcher()" value="{{watcherBtnText}}" /> watched: {{internalCounter}} times<br/>
<strong>Number of $$watchers in $scope:</strong> {{$$watchers.length}}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<script type="text/javascript">
angular.module('app', [])
.controller('myTestCntrl', function myTestCntrl($scope) {
$scope.counter = 0;
$scope.pauseWatching = false;
$scope.watcherBtnText = 'Pause';
$scope.internalCounter = -1;
$scope.increaseCounter = function() {
$scope.counter++;
};
var listenerFn = function() {
if ($scope.pauseWatching) {
namedWatcher();
} else {
$scope.internalCounter++;
};
}
var namedWatcher = $scope.$watch('counter', listenerFn);
$scope.pauseWatcher = function() {
if ($scope.pauseWatching) {
$scope.watcherBtnText = 'Pause';
$scope.pauseWatching = false;
$scope.internalCounter--;
namedWatcher = $scope.$watch('counter', listenerFn);
} else {
$scope.watcherBtnText = 'Continue';
$scope.pauseWatching = true;
namedWatcher();
};
}
});
</script>
</body>
关于jsfiddle的演示:http://jsfiddle.net/BuriB/63sND/