ng-click angularjs上的表单验证 [英] Form validation on ng-click angularjs

查看:83
本文介绍了ng-click angularjs上的表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在现有答案中找到解决方案,因此我将其发布了.

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.

表单中有多个按钮(超过2个),并且使用ng-click绑定到控制器中的功能.

There are buttons (more than 2) in the form and are tied to functions in controllers using ng-click.

在执行该功能之前,我需要先通过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.

我制造了一个小提琴. https://jsfiddle.net/z1uyyqg9/

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>

推荐答案

一个非常简单的解决方案是为表单命名,以便您可以引用它,然后调整ng-click以仅在表单为有效:

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>

叉状提琴: https://jsfiddle.net/r8d1uq0L/

我喜欢从视图中分离验证(与业务有关),为此,我创建了 egkyron 使您可以在代码中定义模型约束,并使用程序验证和标准Angular表单验证.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆