简体   繁体   English

角度验证-表单无效时防止按钮ng-click()

[英]angular validation - prevent button ng-click() when form is invalid

I have an angular form as part of a single page App. 我有一个角形表单,作为单页应用程序的一部分。 The 'Continue' button moves a user to the next section of the app, and has an ng-click. “继续”按钮会将用户移至应用程序的下一部分,并会进行ng单击。 I would like to prevent this ng-click from happening when the button is clicked and the form is invalid, but I don't want to disable the Continue button. 我想防止在单击按钮且表单无效时发生这种ng-click,但是我不想禁用“继续”按钮。

Example: A user comes to the page and immediately clicks the Continue button without providing a first name. 示例:用户来到该页面,然后立即单击继续按钮而不提供名字。 The error message "You should provide a first name" is shown and the user remains on the page. 显示错误消息“您应提供名字”,并且用户保留在页面上。

How can I do this? 我怎样才能做到这一点? Here is the code: 这是代码:

<form name="form" novalidate >

<div ng-show="form.FirstName.$touched && form.FirstName.$error.required" class="errorMessage">
    You must enter a first name
</div>

<div class="form-group">
    <label for="firstName" class="form-label">First Name</label>
    <input id="firstName" class="form-control" name="FirstName" ng-model="vm.user.firstName" required />
</div>

<div class="btn-group">
    <button ng-click="vm.next()">Continue</button>
</div>
</form>

Just add form.$valid && before the function call: 只需在函数调用前添加form.$valid &&

<form name="form" novalidate >

<div ng-show="form.FirstName.$touched && form.FirstName.$error.required" class="errorMessage">
    You must enter a first name
</div>

<div class="form-group">
    <label for="firstName" class="form-label">First Name</label>
    <input id="firstName" class="form-control" name="FirstName" ng-model="vm.user.firstName" required />
</div>

<div class="btn-group">
    <button ng-click="form.$valid && vm.next()">Continue</button>
</div>
</form>

Either a button is disabled or it's clickable, you can't have it both ways. 无论是禁用按钮还是单击按钮,都不能同时使用。

What you could do in your controller for vm.next() is say: 您可以在控制器中为vm.next()执行的操作是:

myApp.controller('Page1Controller'),  ['$scope', function ($scope)
{
    $scope.vm = {};

    $scope.vm.next = function()
    {
        if (! $scope.vm.isFormValid())            
            return;            
        //move to the next page with your current code
        ...
    }

    $scope.vm.isFormValid()
    {
        $scope.vm.shouldShowError = $scope.form.valid; //add vm.shouldShowError to your error message ng-show in the view so it will display only after clicking continue
        return $scope.form.valid;
    }
}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM