ng-click angularjs 上的表单验证 [英] Form validation on ng-click angularjs
问题描述
我无法在现有答案中找到解决方案,因此我发布了这个.
我有一个包含许多输入字段的表单,其中许多是必需的.
表单中有按钮(超过 2 个)并且使用 ng-click 与控制器中的功能相关联.
在执行函数之前,我需要在 ng-click 上验证表单.
默认情况下,表单验证在函数执行后进行.如果未填写必填字段,则函数不应运行.
我创建了一个小提琴.https://jsfiddle.net/z1uyyqg9/
<div ng-app="myApp" ng-controller="myCtrl"><表格><input type="text" ng-model='name' required><button ng-click='preview()'>预览</button><button ng-click='update()'>更新</button></表单>
一个非常简单的解决方案是给表单一个名字,这样你就可以引用它,然后调整 ng-click
仅在表单有效时触发:
分叉小提琴:https://jsfiddle.net/r8d1uq0L/
我喜欢将验证(业务问题)与视图分开,为此我创建了 egkyron允许您在代码中定义模型约束,并使用编程验证和标准 Angular 表单验证.
I am unable to find a solution in the existing answers, hence i am posting this.
I have a form which has many input fields, many of them are required.
There are buttons (more than 2) in the form and are tied to functions in controllers using ng-click.
I need to have form validated on ng-click before the function is executed.
By default, form validation is happening after function execution. Function should not run if required fields are not filled.
I have created a fiddle. https://jsfiddle.net/z1uyyqg9/
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name=undefined;
$scope.preview = function(){
alert("Previewed");
};
$scope.update = function(){
alert("Updated");
}
});
</script>
<div ng-app="myApp" ng-controller="myCtrl">
<form>
<input type="text" ng-model='name' required>
<button ng-click='preview()'>Preview</button>
<button ng-click='update()'>Update</button>
</form>
</div>
A very-very simple solution is to give the form a name so you can refer to it and then tweak the ng-click
to fire only if the form is valid:
<form name="myform">
<input type="text" ng-model='name' ng-required="true" />
<button ng-click="myform.$valid && preview()">Preview</button>
<button ng-click="myform.$valid && update()">Update</button>
</form>
Forked fiddle: https://jsfiddle.net/r8d1uq0L/
I like separating validation (a business concern) from the view, to that end I created egkyron that lets you define the model constraints in code and use programmatic validation along with standard Angular form validation.
这篇关于ng-click angularjs 上的表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!