angularjs-禁用提交直到所有字段都填满

时间:2017-05-08 17:17:16

标签: javascript angularjs

表单中的“提交”按钮应该被禁用,直到所有字段都填满,但我注意到的是当用户只输入用户名按钮时,

<div class="list">
<form id="create" name="pw" method="post">
  <label class="item item-input item-stacked-label">
    <span class="input-label">Username</span>
    <input type="text" placeholder="kojobaah" ng-model="username" required>
</label>

   <label for="password">New Password
    <input type="password" name="user_password" ng-model="user_password" ng-required="confirm_password && !user-password" password-verify="confirm_pasword">
    <p ng-show="pw.user_password.$error.passwordVerify">Passwords do not match</p>
    <p ng-show="pw.user_password.$error.required">This field is required</p>
  </label>
</p>
 <p>
  <label for="password">Confirm Password
    <input type="password" name="confirm_password" ng-model="confirm_password" ng-required="user_password && !confirm_password" password-verify="user_password"> 
    <p ng-show="pw.confirm_password.$error.passwordVerify">Passwords do not match</p>
    <p ng-show="pw.confirm_password.$error.required">This field is required</p>
  </label>
  <br />
  <p align="center"><button ng-disabled="create.$invalid" class="button button-balanced" ng-click="register()">Create Account</button></p>  
  </form>
  </div>

JS

.directive('passwordVerify', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, elem, attrs, ngModel) {
            scope.$watch(attrs.ngModel, function() {
                if (scope.confirm_password === scope.user_password) {
                    scope.pw.confirm_password.$setValidity('passwordVerify', true);
                    scope.pw.user_password.$setValidity('passwordVerify', true);
                } else if (scope.confirm_password !== scope.user_password) {
                    scope.pw.confirm_password.$setValidity('passwordVerify', false);
                    scope.pw.user_password.$setValidity('passwordVerify', false);
                }
            });
        }
     };
})

关于如何在用户名填写且密码匹配之前禁用按钮的任何帮助?

2 个答案:

答案 0 :(得分:2)

您的表单名称为pw,因此您需要深入了解Angular的整体表单有效性指令。

简单地改变:

<button ng-disabled="create.$invalid" 
        class="button button-balanced"
        ng-click="register()">
        Create Account
</button>

为:

<button ng-disabled="pw.$invalid" 
        class="button button-balanced"
        ng-click="register()">
        Create Account
</button>

Working Plunker:http://plnkr.co/edit/0zlN2TmEIbGQW5Mq7YJ0?p=preview

更新:在密码字段上将ng-required切换为简单true,并将比较逻辑移至按钮上的ng-disabled指令,即可实现验证检查。

<button ng-disabled="pw.$invalid || (user_password != confirm_password)" 
        class="button button-balanced"
        ng-click="register()">
        Create Account
</button>

答案 1 :(得分:1)

由于您的表单名称为 pw ,只需将您的CREATE ACCOUNT按钮更改为:

<button ng-disabled="pw.$invalid" 
        class="button button-balanced"
        ng-click="register()">
        Create Account
</button>