Skip to content Skip to sidebar Skip to footer

Unbinding $watch In Angularjs After Called

I know you can unbind a $watch like this: var listener = $scope.$watch('tag', function () {}); // ... listener(); // would clear the watch but can you unbind the watch within the

Solution 1:

you can just do it the same way you already do, call the "deregistration" inside your function:

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

Solution 2:

Because tag is an expression, you can use one-time binding to unbind once the value was received:

$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><scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script><metacharset="utf-8"><metaname="viewport"content="width=device-width"><title>JS Bin</title></head><bodyng-controller="example">
Tag: {{tag}}
<br>
Watch once result: {{tagAsSeen}}
</body></html>

Solution 3:

Solution 4:

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

Solution 5:

Just like a similar question, a slight improvement to @Kris' answer will get you something more sleek and re-usable throughout the project.

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

Post a Comment for "Unbinding $watch In Angularjs After Called"