angular學習筆記(十四)-$watch(3)

詩&遠方發表於2014-05-12

同樣的例子,還可以這樣寫:

<!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實現同一個功能,有多種設計方法,需要考慮它的效能,考慮邏輯性.

目前來說,首先要做到的是能夠以清楚的邏輯將程式設計出來,將來再慢慢考慮效能.

 

 

 

 

 

 

 

 

 

 

 

相關文章