Par*_*ras 2 javascript forms angularjs
我是AngularJS的新手.我正在尝试O'Reilly的AngularJS书中提到的演示.我知道当表单中有一个输入字段时,在该输入中按Enter键会导致触发两者ng-click和ng-submit操作.但是,就我而言,我只有一个输入字段,即使我没有在输入字段中按回车键,每次点击重置按钮时都会调用我的ng-submit动作.这是代码.
<!DOCTYPE html>
<html ng-app="">
<head lang="en">
<meta charset="UTF-8">
<title>Form Submit Action</title>
</head>
<body>
<form ng-submit="requestFunding()"
ng-controller="FormController">
Estimate :
<input ng-model="estimate"/>
<br/>
Recommended :
{{recommended}}
<br/>
<Button>Fund My Start Up</Button>
<Button ng-click="reset()">Reset</Button>
</form>
<script src="Scripts/angular.js"></script>
<script>
function FormController($scope)
{
$scope.estimate = 0;
computeNeeded = function(){
$scope.recommended = $scope.estimate * 10;
};
$scope.$watch('estimate', computeNeeded);
$scope.requestFunding = function()
{
window.alert("Add More Customers First");
};
$scope.reset = function()
{
$scope.estimate = 0;
};
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
有任何逻辑或概念上的错误吗?当我使用AngularJS时,请也告诉我正确的提交和重置表单的方法.
在stardard html中,您需要设置type="reset"为指示这是一个重置按钮:
<button type="reset" ng-click="reset()">Reset</button>
Run Code Online (Sandbox Code Playgroud)
但是你会看到这种方法在角度方面存在问题,正如本DEMO所示.单击时Reset,输入设置为空,而不是您在代码中指定的0:
$scope.reset = function() {
$scope.estimate = 0;
};
Run Code Online (Sandbox Code Playgroud)
出现此问题的原因是您$scope.reset首先运行并被重置按钮的浏览器的默认操作覆盖(清除表单输入).
在angular中,你需要做不同的事情,你需要preventDefault并使用form.$setPristine()来重置表单输入状态:
<form name="form" ng-submit="requestFunding()" ng-controller="FormController"> //give the form a name
Estimate :
<input ng-model="estimate" />
<br/>Recommended : {{recommended}}
<br/>
<button>Fund My Start Up</button>
<button ng-click="$event.preventDefault(); reset(); form.$setPristine();">Reset</button>
</form>
Run Code Online (Sandbox Code Playgroud)
从$ setPristine的文档中调出:
将表单设置为其原始状态.
可以调用此方法来删除'ng-dirty'类并将表单设置为其原始状态(ng-pristine类).此方法还将传播到此表单中包含的所有控件.
当我们想要在保存或重置表单后"重用"表单时,将表单设置回原始状态通常很有用.
| 归档时间: |
|
| 查看次数: |
3619 次 |
| 最近记录: |