angular学习笔记(十四)-$watch(3)
生活随笔
收集整理的這篇文章主要介紹了
angular学习笔记(十四)-$watch(3)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
同樣的例子,還可以這樣寫:
<!DOCTYPE html> <html ng-app> <head><title>11.3$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">{{computeTotal()|currency}}</span></td></tr><tr><td>折扣: <span class="red">{{discount|currency}}</span></td></tr><tr><td>現價: <span class="green">{{computeNow()|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.discount = 0;$scope.computeTotal = function(){var total = 0;for(var i=0; i<$scope.items.length; i++){total += $scope.items[i].quantity*$scope.items[i].price;}return total};$scope.computeDiscount = function(newV,oldV,scope){$scope.discount = newV >= 500 ? newV*0.1 : 0 ;};$scope.computeNow = function(){return $scope.computeTotal() - $scope.discount;};$scope.$watch('computeTotal()',$scope.computeDiscount); }/*
最后這句橙色的,也可以寫成:
$scope.$watch($scope.computeTotal,$scope.computeDiscount)
效果一致
*/
1. 視圖的總價部分,改成computeTotal()
2. $watch監測computeTotal函數返回值的變化
3. 總價變化,則調用computeDiscount函數計算折扣,其中第一個參數就是最新的總價
4. 視圖的現價部分,改成computeNow(),通過總價和折扣計算現價
?
使用這種方法,邏輯上不夠清楚,并且,$scope.computeTotal會被多次執行,影響性能,僅作參考.
-----------------------------------------------------------------------------------------------------------------------
遺留問題:
使用angular實現同一個功能,有多種設計方法,需要考慮它的性能,考慮邏輯性.
目前來說,首先要做到的是能夠以清楚的邏輯將程序設計出來,將來再慢慢考慮性能.
?
?
?
?
?
?
?
?
?
?
?
轉載于:https://www.cnblogs.com/liulangmao/p/3723555.html
總結
以上是生活随笔為你收集整理的angular学习笔记(十四)-$watch(3)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 经典 | 单片机常用外围电路设计
- 下一篇: (一)城市三维基础展示方案