//
// UNBIND .$WATCH
// https://www.bennadel.com/blog/2480-unbinding-watch-listeners-in-angularjs.htm
//
// In some cases you may only want to $watch() for a single change
// or only watch for changes up to a certain point.
// You can unbind a $watch() listener using the provided "deregistration" function.
// When you invoke the $watch() method, to create a binding, AngularJS returns a "deregistration" function
// This function can then be invoked to unbind your $watch() listener
// Example: watch the number of clicks that a link receives.
// And, if that number gets above 5, show a message and remove the listener
<a ng-click="incrementCount()">Click it, click it real good!</a>
{{ clickCount }}
<p ng-show="isShowingFeedback">Heck yeah, now that's how you click a link!!</p>
//
var app = angular.module( "Demo", [] );
app.controller(
"AppController",
function( $scope ) {
// I keep track of how many times the user has clicked
// the link.
$scope.clickCount = 0;
// I determine if the "encouraging" feedback is shown.
$scope.isShowingFeedback = false;
// ---
// WATCHERS.
// ---
// When you call the $watch() method, AngularJS
// returns an unbind function that will kill the
// $watch() listener when its called.
var unbindWatcher = $scope.$watch(
"clickCount",
function( newClickCount ) {
console.log( "Watching click count." );
if ( newClickCount >= 5 ) {
$scope.isShowingFeedback = true;
// Once the feedback has been displayed,
// there's no more need to watch the change
// in the model value.
unbindWatcher();
}
}
);
// ---
// PUBLIC METHODS.
// ---
// I increment the click count.
$scope.incrementCount = function() {
$scope.clickCount++;
// NOTE: You could just as easily have called a
// counter-related method right here to test when
// to show feedback. I am just demonstrating an
// alternate approach.
};
}
);
//we're storing the function reference returned by the $watch() statement;
//then, once the $watch() fires a few times, we invoke that stored method, unbinding the $watch() listener.