同樣是上一個例子,我們要求並非實時的計算結果,而是等到使用者確定自己已經輸入完畢,然後進行計算:
<!DOCTYPE html> <html ng-app> <head> <title>2.3.4計算階乘例項3</title> <meta charset="utf-8"> <script src="../angular.js"></script> <script src="script.js"></script> </head> <body> <div ng-controller = 'Factorial'> <form action="" ng-submit="compute()"> <input type="text" ng-model="factorial.number"/> 的階乘結果是: <span>{{factorial.result}}</span> <br> <button>計算</button> <br> <button ng-click="reset()">重置</button> </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); }; $scope.reset = function () { $scope.factorial.number = 0; $scope.factorial.result = 1; }; }
去掉了$watch對factorial.number的監測,而是在表單被提交的時候才進行計算,然後點選重置的時候,將number和result進行重置
angular對dom元素繫結事件的規則如下:
onclick --- ng-click
ondblclick --- ng-dblclick
...
*其實兩個button都是會觸發form的提交事件的.
*比較好的方法是把compute()寫在計算button的ng-click裡,這裡僅作演示ng-submit