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() });
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.
scope. $watch returns a function that you can call and that will unregister the watch.
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.
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.
you can just do it the same way you already do, call the "deregistration" inside your function:
var unbind = $scope.$watch("tag", function () { // ... unbind(); });
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With