原文: 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. DLP与上网行为管理的差别总结

    参考网康和深信服的上网行为管理手册,总结了一下DLP与上网行为管理的差别: DLP与上网行为管理在功能和使用目的上有很大不同.主要体现在: 上网行为管理主要是对用户访问目标URL过滤,应用端口限制,上 ...

  2. [CQOI2018]异或序列 (莫队,异或前缀和)

    题目链接 Solution 有点巧的莫队. 考虑到区间 \([L,R]\) 的异或和也即 \(sum[L-1]~\bigoplus~sum[R]\) ,此处\(sum\)即为异或前缀和. 然后如何考虑 ...

  3. android工程下assets与raw文件夹

    在应用的开发中,当我们创建一个新的Android工程后,我们会发现工程中包含了一个目录assets,另外当我们察看一些示例工程的时候,有时会发现在该工程的资源目录下会有一个raw目录(res/raw) ...

  4. saltstack 实现haproxy+keepalived

    1.目录结构规划如下 mkdir -p /srv/salt/prod/haproxy mkdir -p /srv/salt/prod/keepalived mkdir -p /srv/salt/pro ...

  5. 使序列有序的最少交换次数(minimum swaps)

    交换相邻两数 如果只是交换相邻两数,那么最少交换次数为该序列的逆序数. 交换任意两数 数字的总个数减去循环节的个数?? A cycle is a set of elements, each of wh ...

  6. 模拟Json格式传值请求与数据接收

    a.php代码: function http_post_json($url, $jsonStr) { $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, ...

  7. 结构型设计模式之适配器模式(Adapter)

    结构 意图 将一个类的接口转换成客户希望的另外一个接口.A d a p t e r 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作. 适用性 你想使用一个已经存在的类,而它的接口不符合你 ...

  8. 莫队 [洛谷2709] 小B的询问[洛谷1903]【模板】分块/带修改莫队(数颜色)

    莫队--------一个优雅的暴力 莫队是一个可以在O(n√n)内求出绝大部分无修改的离线的区间问题的答案(只要问题满足转移是O(1)的)即你已知区间[l,r]的解,能在O(1)的时间内求出[l-1, ...

  9. Linux之epoll详细解析实现

    /* * fs/eventpoll.c (Efficient event retrieval implementation) * Copyright (C) 2001,...,2009 Davide ...

  10. Linux C/C++内存泄漏检测工具:Valgrind

    Valgrind 是一款 Linux下(支持 x86.x86_64和ppc32)程序的内存调试工具,它可以对编译后的二进制程序进行内存使用监测(C语言中的malloc和free,以及C++中的new和 ...