Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 watch function declaration. So after the watch gets executed once, it unbinds itself? Something like:

$scope.$watch("tag", function () {     unbindme() }); 
like image 736
Michael Avatar asked Oct 16 '13 02:10

Michael


People also ask

How does $Watch work in AngularJS?

What is the angular JS watch function? The angular JS $watch function is used to watch the scope object. The $watch keep an eye on the variable and as the value of the variable changes the angular JS $what runs a function. This function takes two arguments one is the new value and another parameter is the old value.

How to destroy watch in AngularJS?

scope. $watch returns a function that you can call and that will unregister the watch.

How to stop or deactivate the watch in AngularJS?

When you invoke the $watch() method, to create a binding, Angular JS returns a "de-registration" function. This function can then be used to unbind your $watch() listener - all you have to do is invoke this returned function and your $watch() listener will be removed.

When to use $apply in AngularJS?

In AngularJS, $apply() function is used to evaluate expressions outside of the AngularJS context (browser DOM Events, XHR). Moreover, $apply has $digest under its hood, which is ultimately called whenever $apply() is called to update the data bindings.


2 Answers

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

var unbind = $scope.$watch("tag", function () {     // ...     unbind(); }); 
like image 121
Kris Ivanov Avatar answered Oct 03 '22 20:10

Kris Ivanov


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>  <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>
like image 28
Klaster_1 Avatar answered Oct 03 '22 20:10

Klaster_1