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>
相關文章
相關標籤/搜索