AngularJS系统学习之$watch(监控)

在scope的内置的所有函数中,用的最多的可能就是$watch函数了, 当你的数据模型中某一部分发生变化时,$watch函数可以向你发出通知。 你可以监控单个对象的属性,亦可以监控需要经过计算的结果(函数), 实际上只要能够被当做属性访问到, 或者可以当做一个Java函数被计算出来, 就可以被$wacth函数监控。它的函数签名为: 

$watch (watchFn, watchAction, deepWatch)

其中watchFn

这个参数是一个带有Angular表达式或者函数的字符串, 它会返回被监控函数的数据模型的当前值。

  watchAction

这是一个函数表达式, 当watchFn发生变化时会被调用。

  deepWatch

如果设置为true, 这个可选的布尔型参数将会命令Angular去检查被监控对象的每个属性是否发生了变化。若果你想要监控数组中的元素, 或者对象上的所有属性, 而不只是监控一个简单的值, 就可以设置为true。

 写了一个小例子,大家可以看看。

 1 <!DOCTYPE>
 2 <html ng-app='myApp'>
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Your Shopping Cart</title>
 6     <script src="../../../vendor/angular/angular.js"></script>
 7     <script src="../../../vendor/angular/angular-route.js"></script>
 8 </head>
 9 <body ng-controller='CartController'>
10 <h1>Your order</h1>
11 
12 <div ng-repeat="item in items">
13     <span>{{item.title}}</span>
14     <input ng-model='item.quantity'>
15     <span>{{item.price | currency}}</span>
16     <span>{{item.price * item.quantity | currency}}</span>
17     <div>Total:{{totalCart()}}</div>
18     <div>Discount: {{bill.discount}}</div>
19     <div>Subtatal: {{subtotal()}}</div>
20 </div>
21 
22 <script>
23     var myAppMoudle = angular.module('myApp', []);
24     myAppMoudle.controller('CartController', ['$scope', function ($scope) {
25         $scope.bill={};
26         $scope.discount = 2;
27         $scope.items = [{title: 'paint', quantity: 8, price: 3.95},
28             {title: 'pa', quantity: 7, price: 3.95},
29             {title: 'paa', quantity: 17, price: 3.95},
30             {title: 'paaa', quantity: 177, price: 3.95}];
31         $scope.totalCart = function () {
32             var total = 0;
33             for(var i = 0, len = $scope.items.length; i < len; i++){
34                 total = total + $scope.items[i].price * $scope.items[i].quantity;
35             }
36             return total;
37         }
38 
39         $scope.subtotal = function () {
40             return $scope.totalCart() - $scope.discount;
41         };
42 
43         function calculateDiscount(newValue, oldValue, scope) {
44             $scope.bill.discount = newValue > 100 ? 10 : 0;
45         }
46 
47         $scope.$watch($scope.totalCart, calculateDiscount);
48     }]);
49 </script>
50 </body>
51 </html>
原文地址:https://www.cnblogs.com/wangnuo/p/6322098.html