2013-10-16 4 views
23

라고 나는이 같은 $ 시계 바인딩을 해제 할 수 있습니다 알고 있습니다. 그래서 시계가 한 번 실행되면 자체 바인딩 해제됩니까? 같은 : 당신이 당신이 이미와 동일한 방식으로 다만 수

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

에 http : // 유래를 .com/a/13652152/33 3777이 적합해야합니다. –

답변

49

은 함수 내부의 "등록 취소"를 호출 당신이 필요로하는

var unbind = $scope.$watch("tag", function() { 
    // ... 
    unbind(); 
}); 
+18

'listener'는'unbind'라는 이름이 좋습니다. – daniellmb

+0

@daniellmb 'listener()'를 한 번 더 호출하면 무엇이 잘못됩니까? 나는 조건이 만족 될 때만'listener()'가 실행되는 코드 조각을 가지고있다. 그래서 (만약'scope. $ on ('destroy')') 안쪽에 다시 바인딩 해제 함수를 호출하면 그 문제는 해결 될 수 있습니까? – Dane

+1

@ 데인 당신도 원하는대로 여러 번 호출 할 수 있습니다. 테스트도 쉽습니다. –

7

때문에 값이 수신되면 바인딩을 해제 할 one-time binding를 사용할 수 있습니다

$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>

0
var unbindMe=$scope.$watch('tag',function(newValue){ 
    if(newValue){ 
     unbindMe() 
    } 
})