28

次のように $watch のバインドを解除できることはわかっています。

var listener = $scope.$watch("tag", function () {});
// ...
listener(); // would clear the watch

ただし、ウォッチ関数宣言内でウォッチのバインドを解除できますか。では、watch が一度実行されると、それ自体がアンバインドされるのでしょうか? 何かのようなもの:

$scope.$watch("tag", function () {
    unbindme()
});
4

5 に答える 5

58

すでに行っているのと同じ方法で、関数内で「登録解除」を呼び出します。

var unbind = $scope.$watch("tag", function () {
    // ...
    unbind();
});
于 2013-10-16T02:34:41.140 に答える
9

tagは式であるため、値を受け取ったら、ワンタイム バインドを使用してバインドを解除できます。

$scope.$watch("::tag", function () {});

angular
.module('app', [])
.controller('example', function($scope, $interval) {
  $scope.tag = undefined
  $scope.$watch('::tag', function(tag) {
    $scope.tagAsSeen = tag
  })
  $interval(function() {
    $scope.tag = angular.isDefined($scope.tag) ? $scope.tag + 1 : 1
  }, 1000)
})
angular.bootstrap(document, ['app'])
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body ng-controller="example">
Tag: {{tag}}
<br>
Watch once result: {{tagAsSeen}}
</body>
</html>

于 2016-06-22T07:56:05.580 に答える
0
var unbindMe=$scope.$watch('tag',function(newValue){
    if(newValue){
       unbindMe()
    }
})
于 2016-06-22T08:03:17.943 に答える