AngularJS学习——价格计算器

利用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>

 

 

 

posted @ 2016-07-07 16:20  奔跑的蜗牛~  阅读(1615)  评论(0编辑  收藏  举报