Mic*_*ael 28 javascript frameworks angularjs
我知道你可以解开像这样的$ watch:
var listener = $scope.$watch("tag", function () {});
// ...
listener(); // would clear the watch
Run Code Online (Sandbox Code Playgroud)
但你可以在手表功能声明中取消绑定手表吗?因此,在手表执行一次后,它会自行解除绑定吗?就像是:
$scope.$watch("tag", function () {
unbindme()
});
Run Code Online (Sandbox Code Playgroud)
Kri*_*nov 58
你可以像你现在一样做,在你的功能中调用"注销":
var unbind = $scope.$watch("tag", function () {
// ...
unbind();
});
Run Code Online (Sandbox Code Playgroud)
因为tag是表达式,所以一旦收到值,就可以使用一次性绑定取消绑定:
$scope.$watch("::tag", function () {});
Run Code Online (Sandbox Code Playgroud)
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'])Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)