標籤:
利用AngularJs實現價格計算機,總價滿100免運費。(熟悉$watch的使用)
代碼:
<!DOCTYPE html><html lang="en" ng-app="myApp"><head> <meta charset="UTF-8"> <title>價格計算機</title> <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css"></head><body> <div class="container" ng-controller="MyControl"> <h2>價格計算機</h2> 單價:<input type="text" class="form-control" ng-model="iphone.price"> 數量:<input type="text" class="form-control" ng-model="iphone.num"> <hr> <p>總價:{{ sum() | currency:‘¥‘}}</p> <p>運費:{{ iphone.yf | currency:‘¥‘}}</p> <p>合計:{{ sum() + iphone.yf | currency:‘¥‘}}</p> </div> <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script> <script> var myAng = angular.module(‘myApp‘,[]); myAng.controller(‘MyControl‘,function($scope){ $scope.iphone = { price:10, num:1, yf:10 } $scope.sum = function(){ return $scope.iphone.price*$scope.iphone.num } // $watch監控對象為屬性時,不加$scope $scope.$watch(‘iphone.num‘,function(newvalue,oldvalue){ console.log(‘新值:‘+ newvalue +‘;舊值:‘+ oldvalue) }) // $watch監控對象為方法時,加$scope $scope.$watch($scope.sum,function(newvalue,oldvalue){ return $scope.iphone.yf = newvalue >= 100 ? 0 : 10; }) }) </script></body></html>
AngularJS學習——價格計算機