原文: https://www.bennadel.com/blog/2480-unbinding-watch-listeners-in-angularjs.htm

-----------------------------------------------------------------------------

Unbinding $watch() Listeners In AngularJS

By Ben Nadel on June 5, 2013

In AngularJS, you can watch for changes in your view-model by binding a listener to a particular statement (or function) using the $scope's $watch() method. You tell the $watch() method what to examine and AngularJS will invoke your listener whenever the item-under-scrutiny changes. In the vast majority of cases, the $watch() statement can be run with a set-and-forget mentality. But, in rare cases, you may only want to $watch() for a single change; or, only watch for changes up to a certain point. If that's the case, 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 used to unbind your $watch() listener - all you have to do is invoke this returned function and your $watch() listener will be removed.

To see this in action, take a look at the following code. In this demo, we're watching the number of clicks that a link receives. And, if that number gets above 5, we're going to show a message; however, once the message is shown, we remove the listener as it will no longer have any value.

  <!doctype html>
  <html ng-app="Demo" ng-controller="AppController">
  <head>
  <meta charset="utf-8" />
   
  <title>
  Unbinding $watch() Listeners In AngularJS
  </title>
  </head>
  <body>
   
  <h1>
  Unbinding $watch() Listeners In AngularJS
  </h1>
   
  <p>
  <a ng-click="incrementCount()">Click it, click it real good!</a>
  &raquo;
  {{ clickCount }}
  </p>
   
  <p ng-show="isShowingFeedback">
  <em>Heck yeah, now that's how you click a link!!</a>
  </p>
   
   
   
  <!-- Load jQuery and AngularJS from the CDN. -->
  <script
  type="text/javascript"
  src="//code.jquery.com/jquery-2.0.0.min.js">
  </script>
  <script
  type="text/javascript"
  src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js">
  </script>
  <script type="text/javascript">
   
   
  // Create an application module for our demo.
  var app = angular.module( "Demo", [] );
   
   
  // -------------------------------------------------- //
  // -------------------------------------------------- //
   
   
  // Define the root-level controller for the application.
  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.
   
  };
   
  }
  );
   
   
  </script>
   
  </body>
  </html>
view rawunbind-watch.htm hosted with ❤ by GitHub

As you can see, 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. If you watch the video, you can see that the console.log() statements stop as soon as the "deregistration" function is called.

Most of the time, you won't need to use this. In fact, I only found out about this feature yesterday when I ran into a situation in which I needed to unbind the $watch() listener. That said, it turns out it's rather easy, as long as you know it's there.

Unbinding $watch() Listeners In AngularJS的更多相关文章

  1. AngularJS 源码分析2

    上一篇地址 本文主要分析RootScopeProvider和ParseProvider RootScopeProvider简介 今天这个rootscope可是angularjs里面比较活跃的一个pro ...

  2. [译]AngularJS $apply, $digest, 和$evalAsync的比较

    原文:The differences between AngularJS $apply, $digest, and $evalAsync 你是不是也常在想AngularJS $apply, $dige ...

  3. Angularjs 双向绑定机制解析

    文章转自:http://www.2cto.com/kf/201408/327594.html AngularJs 的元素与模型双向绑定依赖于循环检测它们之间的值,这种做法叫做脏检测,这几天研究了一下其 ...

  4. angularjs 指令(directive)详解(1)

    原文地址 什么是directive?我们先来看一下官方的解释: At a high level, directives are markers on a DOM element (such as an ...

  5. Speeding up AngularJS apps with simple optimizations

    AngularJS is a huge framework with that already has many performance enhancements built in, but they ...

  6. 转:在控制台中调试AngularJS应用

    在控制台中调试AngularJS应用 在创建AngularJS应用时,一个很棘手的问题是如何在Chrome,Firefox,以及IE的JavaScript控制台中访问深藏在应用中的数据和服务.本文将会 ...

  7. AngularJS 3

    AngularJS 源码分析3 本文接着上一篇讲 上一篇地址 回顾 上次说到了rootScope里的$watch方法中的解析监控表达式,即而引出了对parse的分析,今天我们接着这里继续挖代码. $w ...

  8. angularJS 系列(七)---指令

    ----------------------------------------------------------------------------------- 原文:https://www.s ...

  9. 深入理解AngularJs-scope(一)

    进入正文前的说明:本文中的示例代码并非AngularJs源码,而是来自书籍<<Build Your Own AngularJs>>, 这本书的作者仅依赖jquery和lodas ...

随机推荐

  1. 身为多年的ubuntu用户。。。

    在这之前 说是多年也没有多年,事实上也就两年.. 不得不说一句,终于承受不住不稳定之重了... 个人觉得开始还是从centos开始比较好,比如说现在的我.. 之前看过的不知道在哪里的文章,谈论的是ub ...

  2. es6+最佳入门实践(4)

    4.函数扩展 4.1.参数默认值 默认参数就是当用户没有传值的时候函数内部默认使用的值,在es5中我们通过逻辑运算符||来实现 function Fn(a, b) { b = b || "n ...

  3. 行为型设计模式之访问者模式(Visitor)

    结构 意图 表示一个作用于某对象结构中的各元素的操作.它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作. 适用性 一个对象结构包含很多类对象,它们有不同的接口,而你想对这些对象实施一些依 ...

  4. Spring3.2+Struts2.3+Mybatis3.2整合使用(注解使用)

    0.包结构:

  5. Juce-强大的开源类库

    介绍 Juce是一个完全围绕C++语言的类库,用来开发跨平台的应用程序. 完整的用doxgen生成的html形式的API手册可以在这里下到.或者可以从下载页面下载预编译的windows帮助文件. 想获 ...

  6. 多线程之:竞态条件&临界区

    竞态条件指:当一个对象或者一个不同步的共享状态,被两个或者两个以上的线程修改时,对访问顺序敏感,则会产生竞态条件. 临界区指:导致竞态条件发生的代码区. 如:increase块为临界区 public ...

  7. 控制台注入DLL代码

    // zhuru.cpp : 定义控制台应用程序的入口点. #include "stdafx.h" #include <Windows.h> #define GameC ...

  8. 计蒜客 28449.算个欧拉函数给大家助助兴-大数的因子个数 (HDU5649.DZY Loves Sorting) ( ACM训练联盟周赛 G)

    ACM训练联盟周赛 这一场有几个数据结构的题,但是自己太菜,不会树套树,带插入的区间第K小-替罪羊套函数式线段树, 先立个flag,BZOJ3065: 带插入区间K小值 计蒜客 Zeratul与Xor ...

  9. C# api基础1

    1.创建一个简单的api 目录结构 再创建一个controller用来测试 public class DefaultController : ApiController { public string ...

  10. 华农oj 2192: hzk又在打人【CRT合并/待补】

    2192: hzk又在打人 Time Limit: 12 Sec Memory Limit: 512 MB Submit: 52 Solved: 1 [Submit][Status][Web Boar ...