zoukankan      html  css  js  c++  java
  • $watch简单使用

    $watch是一个scope函数,用于监听模型变化,当你的模型部分发生变化时它会通知你。

    $watch(watchExpression, listener, objectEquality);

    每个参数的说明如下:

    1. watchExpression:监听的对象,它可以是一个angular表达式如'name',或函数如function(){return $scope.name}。

    2. listener:当watchExpression变化时会被调用的函数或者表达式,它接收3个参数:newValue(新值), oldValue(旧值), scope(作用域的引用)

    3. objectEquality:是否深度监听,如果设置为true,它告诉Angular检查所监控的对象中每一个属性的变化. 如果你希望监控数组的个别元素或者对象的属性而不是一个普通的值, 那么你应该使用它

    4. 举个栗子:

      $scope.name = 'hello';

      var watch = $scope.$watch('name',function(newValue,oldValue, scope){

              console.log(newValue);

              console.log(oldValue);

      });

      $timeout(function(){

              $scope.name = "world";

      },1000);

      $watch性能问题

      太多的$watch将会导致性能问题,$watch如果不再使用,我们最好将其释放掉。

      $watch函数返回一个注销监听的函数,如果我们想监控一个属性,然后在稍后注销它,可以使用下面的方式:

      var watch = $scope.$watch('someModel.someProperty', callback);

      //...

      watch();

      还有2个和$watch相关的函数:

      $watchGroup(watchExpressions, listener);

      $watchCollection(obj, listener); 

    再举个例子:

     1 <div  ng-controller="watchCtrl"  ng-if="isShow">
     2     <input type="text" ng-model="one">
     3     <input type="text" ng-model="two">
     4     <input type="text" ng-model="three">
     5 </div>
     6 <script src="../lib/angular/angular.js"></script>
     7 <script>
     8  angular.module('zfpxMod',[]);
     9  angular.module('zfpxMod').controller('watchCtrl',function($rootScope,$scope,$timeout){
    10 
    11      $scope.$watch('one',function(newVal,oldVal){
    12          $scope.two = newVal;
    13          $scope.one = Math.random();
    14      });
    15      $scope.$watch('two',function(newVal,oldVal){
    16          $scope.three = newVal;
    17 
    18      });
    19 
    20  });

    $watch 侦听到input:One里的值,将input新输入的值的变化作为参数传给two,two的值再传给there;

  • 相关阅读:
    Leetcode 538. Convert BST to Greater Tree
    Leetcode 530. Minimum Absolute Difference in BST
    Leetcode 501. Find Mode in Binary Search Tree
    Leetcode 437. Path Sum III
    Leetcode 404. Sum of Left Leaves
    Leetcode 257. Binary Tree Paths
    Leetcode 235. Lowest Common Ancestor of a Binary Search Tree
    Leetcode 226. Invert Binary Tree
    Leetcode 112. Path Sum
    Leetcode 111. Minimum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/xu-blog/p/6726701.html
Copyright © 2011-2022 走看看