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

时间:2015-11-13 15:05:45

标签: angularjs forms validation

我有一个角形表单作为单页面应用程序的一部分。继续'按钮将用户移动到应用程序的下一部分,并具有ng-click。我想防止在单击按钮并且表单无效时发生此ng-click,但我不想禁用“继续”按钮。

示例:用户进入该页面并立即单击“继续”按钮而不提供名字。错误消息"您应该提供名字"显示,用户仍然在页面上。

我该怎么做?这是代码:

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

2 个答案:

答案 0 :(得分:8)

只需在函数调用之前添加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>

答案 1 :(得分:2)

按钮被禁用或可点击,你不能双管齐下。

你可以在控制器中为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;
    }
}]);