javascript 调用后在 angularjs 中解除绑定 $watch
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19394204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unbinding $watch in angularjs after called
提问by Michael
I know you can unbind a $watch like this:
我知道你可以像这样解除 $watch 的绑定:
var listener = $scope.$watch("tag", function () {});
// ...
listener(); // would clear the watch
but can you unbind the watch within the watch function declaration. So after the watch gets executed once, it unbinds itself? Something like:
但是你可以在 watch 函数声明中解绑手表吗?那么在手表执行一次后,它会自行解除绑定吗?就像是:
$scope.$watch("tag", function () {
unbindme()
});
回答by Kris Ivanov
you can just do it the same way you already do, call the "deregistration" inside your function:
你可以像你已经做的那样做,在你的函数中调用“注销”:
var unbind = $scope.$watch("tag", function () {
// ...
unbind();
});
回答by Klaster_1
Because tag
is an expression, you can use one-time bindingto unbind once the value was received:
因为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>
回答by Wei Liu
回答by Arun Redhu
var unbindMe=$scope.$watch('tag',function(newValue){
if(newValue){
unbindMe()
}
})
回答by Hashbrown
Just like a similar question, a slight improvement to @Kris' answer will get you something more sleek and re-usable throughout the project.
就像一个类似的问题一样,对@Kris 的回答稍作改进将使您在整个项目中变得更加时尚和可重用。
.run(function($rootScope) {
$rootScope.see = function(v, func) {
var unbind = this.$watch(v, function() {
unbind();
func.apply(this, arguments);
});
};
})
Now thanks to scope prototypical inheritance you can simply go
现在多亏了范围原型继承,你可以简单地去
$scope.see('tag', function() {
//your code
});
And not worry about unbinding at all.
并且根本不用担心解除绑定。