日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

angular学习笔记(十四)-$watch(3)

發布時間:2023/12/14 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。