angular學習筆記(五)-階乘計算例項(1)

詩&遠方發表於2014-05-07
<!DOCTYPE html>
<html ng-app>
<head>
  <title>2.3.2計算階乘例項1</title>
  <meta charset="utf-8">
  <script src="../angular.js"></script>
  <script src="script.js"></script>
</head>
<body>
  <div ng-controller = 'Factorial'>
    <form action="">
      <input type="text" ng-model="factorial.number" ng-change="compute()"/>
      的階乘結果是:
      <span>{{factorial.result}}</span>
    </form>
  </div>
</body>
</html>
function Factorial ($scope) {
    $scope.factorial = {};
    $scope.factorial.number = 0;
    $scope.factorial.result = 1;
    $scope.factorialNum = function(num){
        if(num==0){
            return 1;
        }
        else {
            return num*$scope.factorialNum(--num);
        }
    };
    $scope.compute = function(){
        $scope.factorial.result = $scope.factorialNum($scope.factorial.number);
    }
}

1.ng-model:

將input元素與factorial.number進行繫結

 

2.ng-change:

給input元素的change事件繫結回撥函式為compute方法

 

3.{{factorial.result}}

compute方法會通過factorial.number的值計算factorial.result的值,然後factorial.result的值是和ui進行繫結的.所以,input的value值改變時,span中相應的值也會改變

 

相關文章