AngularJS - Watch 监听对象

<body>
    <div ng-app="myApp">

        <div ng-controller="firstController">
            <p>价格:<input type="text" ng-model="iphone.money"></p>
            <p>个数:<input type="text" ng-model="iphone.num"></p>
            <p>费用:<span>{{ sum() | currency:'¥' }}</span></p>
            <p>运费:<span>{{iphone.fre | currency:'¥'}}</span></p>
            <p>总额:<span>{{ sum() + iphone.fre | currency:'¥'}}</span></p>
        </div>
    </div>
    <script type="text/javascript">
        var app = angular.module("myApp", []);
         
          app.controller('firstController', ['$scope', function ($scope) {
              //对象定义
              $scope.iphone = {
                  money: 5,
                  num: 1,
                  fre: 10
              };

              //计算总量和个数
              $scope.sum = function () {
                  return $scope.iphone.money * $scope.iphone.num;
              }
              //如果总价大于100,运费变成0  可以监听函数,也可以直接监听对象属性
              $scope.$watch($scope.sum,function (newValue,oldValue) {

                  $scope.iphone.fre = newValue >= 100 ? 0 : 10;

              });

          }]);
         
    </script>

</body>

 

posted @ 2016-04-04 22:49  MrMrCash  阅读(596)  评论(0编辑  收藏  举报