angular学习笔记,十四-$watch

同样的例子,还可以这样写:

<!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实现同一个功能,有多种设计方法,需要考虑它的性能,考虑逻辑性.

目前来说,首先要做到的是能够以清楚的逻辑将程序设计出来,将来再慢慢考虑性能.