AngularJs學習筆記(一)----------關於數據綁定

<!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:css

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