同样是上一个例子,我们要求并非实时的计算结果,而是等到用户确定自己已经输入完毕,然后进行计算:
<!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
时间: 2024-10-08 12:34:56