<!DOCTYPE html5>
<html>
    <head>
        <title>AngularJs的练习</title>
        <meta charset="UTF-8"/>
        <link rel="stylesheet" href="css/3.css"/>
    </head>
    <body ng-app="myModule1">
        <h1>AngularJs中关于数据绑定</h1>
        <h3>初识双向数据绑定</h3>
            <label for="uname">单价:</label><input type="text" id="uname" ng-model="price"/>
            <label for="num">数量:</label><input type="text" id="num" ng-model="count"/>
            <span>小计:{{ price*count }}</span>
        <hr/>
        <h3>$watch的练习</h3>
        <div ng-controller="myCtrl1">
            <label for="uname">单价:</label><input type="text" id="uname" ng-model="price"/>
            <label for="num">数量:</label><input type="text" id="num" ng-model="count"/>
            <span>小计:{{ sum }}</span><!--此处的sum是mode->view的单向绑定,故需要$watch监听完成所需功能-->
        </div>
    
        <script src="js/angular.js"></script>
        <script src="js/3.js"></script>
    </body>
</html>

对应的Js:

angular.module('myModule1',[])
       .controller('myCtrl1',function($scope){
               $scope.price=0;
               $scope.count=0;
               $scope.sum=$scope.price*$scope.count;

               // $watch函数返回一个注销监听的函数
               $scope.$watch('price',function(newVal,oldVal){
                   $scope.sum=newVal*$scope.count;//当价格发生变化时,更新sum
               });
               $scope.$watch('count',function(newVal,oldVal){
                   $scope.sum=newVal*$scope.price;
               });
       });

 

posted on 2016-10-23 12:55  木槿惜年  阅读(441)  评论(0编辑  收藏  举报