欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

关于angular js_$watch监控属性和对象详解

程序员文章站 2022-11-20 10:43:26
$watch:(监听一个model,当一个model每次改变时,都会触发第二个函数) $watch('watchfn',watchaction,deepwatch) w...

$watch:(监听一个model,当一个model每次改变时,都会触发第二个函数)

$watch('watchfn',watchaction,deepwatch)

watchfn:带有angular 表达式或者函数的字符串,它会返回被监控的数据模型的当前值。

watchaction: 一个函数function(newvalue,oldvalue){},当watchfn 发生变化时会被调用

deepwatch:默认为false,监听数组的某个元素或者对象的属性时设置为true;

监控一个属性:

<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
</head>
<body>
<div ng-app="myapp" ng-controller="myctrl">
  <form>
    <div class="form-group">
      <input ng-model="name" />{{name}}
      <p>改变次数{{count}}</p>
    </div>
  </form>
</div>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script type="text/javascript">
  
  var app = angular.module('myapp', []);
  app.controller('myctrl', function ($scope){
    $scope.name = '橘子';
    $scope.count = 0;
    $scope.$watch('name', function (newvalue, oldvalue) {
      $scope.count++;
      if($scope.count >5){
        $scope.name = '苹果';
      }
    });
  });
</script>
</body>
</html>

监控一个对象(deepwidth为true)

<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
</head>
<body>
<div ng-app="myapp" ng-controller="myctrl">
  <form>
    <div class="form-group">
      <input ng-model="data.name" />{{data.name}}
      <p>改变次数{{count}}</p>
    </div>
  </form>
</div>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script type="text/javascript">

  var app = angular.module('myapp', []);
  app.controller('myctrl', function ($scope){
    $scope.data = { name: '橘子' };
    $scope.count = 0;
    $scope.$watch('data', function (newvalue, oldvalue) {
      if(newvalue == oldvalue)
      return;
      $scope.count++;
      if($scope.count >5){
         $scope.data.name = '苹果';
      }
    }, true);
  });
</script>
</body>
</html>

以上这篇关于angular js_$watch监控属性和对象详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。