下面來看一個$watch的比較複雜的例子:
還是回到http://www.cnblogs.com/liulangmao/p/3700919.html一開始講的購物車例子,
給它新增一個計算總價和折扣的功能,如果總價超過500,則優惠10%:
程式碼如下:
<!DOCTYPE html> <html ng-app> <head> <title>11.1$watch監控資料變化</title> <meta charset="utf-8"> <script src="../angular.js"></script> <script src="script.js"></script> </head> <body> <div ng-controller="CartController"> <h1>your shopping cart</h1> <table> <tr ng-repeat="item in items"> <td>{{item.title}}</td> <td><input ng-model="item.quantity"/></td> <td>{{item.price|currency}}</td> <td class="red">{{item.price*item.quantity|currency}}</td> <td><button ng-click="remove($index)">remove</button></td> </tr> </table> <hr> <table> <tr> <td>總價: <span class="del">{{bill.all|currency}}</span></td> </tr> <tr> <td>折扣: <span class="red">{{bill.discount|currency}}</span></td> </tr> <tr> <td>現價: <span class="green">{{bill.now|currency}}</span></td> </tr> </table> </div> </body> </html>
function CartController ($scope) { $scope.items = [ {"title":"兔子","quantity":1,"price":"100"}, {"title":"喵","quantity":2,"price":"200"}, {"title":"狗只","quantity":1,"price":"400"}, {"title":"倉鼠","quantity":1,"price":"300"} ]; $scope.remove = function(index){ $scope.items.splice(index,1) }; $scope.bill = { "all":0, "discount":0, "now":0 }; $scope.compute = function(){ var total = 0; for(var i=0; i<$scope.items.length; i++){ total += $scope.items[i].quantity*$scope.items[i].price; } $scope.bill.all = total; $scope.bill.discount = total >= 500 ? total*0.1 : 0 ; $scope.bill.now = $scope.bill.all - $scope.bill.discount }; $scope.$watch('items',$scope.compute,true); }
把需要計算的三個資料: 總價,折扣,現價,放在一個bill物件中,
監測商品列表items陣列的變化,設定$watch的第三個引數為true,這樣,商品的資料一旦發生變化,就會呼叫compute方法,重新計算bill物件中的三個資料
這個例子的js還可以寫成這樣:
function CartController ($scope) { $scope.items = [ {"title":"兔子","quantity":1,"price":"100"}, {"title":"喵","quantity":2,"price":"200"}, {"title":"狗只","quantity":1,"price":"400"}, {"title":"倉鼠","quantity":1,"price":"300"} ]; $scope.remove = function(index){ $scope.items.splice(index,1) }; $scope.bill = { "all":0, "discount":0, "now":0 }; $scope.compute = function(){ var total = 0; for(var i=0; i<$scope.items.length; i++){ total += $scope.items[i].quantity*$scope.items[i].price; } $scope.bill.all = total; $scope.bill.discount = total >= 500 ? total*0.1 : 0 ; $scope.bill.now = $scope.bill.all - $scope.bill.discount }; $scope.$watch($scope.compute); }
差別只有最後一句紅色的程式碼,把$watch的第一個引數從原來的items陣列直接改為compute函式.也就是上一篇http://www.cnblogs.com/liulangmao/p/3722885.html講到的$watch第一個引數的第4種情況.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
遺留問題同上一篇,不清楚直接在$watch的第一個引數中傳入函式時,究竟在監測什麼東西的變化.