无需提交按钮即可验证角形

时间:2017-02-18 03:52:25

标签: html angularjs

我正在使用anuglar.js表单验证。 我想在没有表单提交按钮的情况下检查验证。

这是我的HTML。

<form name="userForm">
  <input type="hidden" ng-model="StandardID" />
  <div class="form-group">
    <label for="email">Name:</label>
    <input type="text" class="form-control" ng-model="Name" placeholder="Name" maxlength="50" required>
    <span ng-show="userForm.Name.$dirty && !userForm.Name.$valid">Name is required.</span>
  </div>
  <div class="form-group">
    <label for="pwd">Alias:</label>
    <input type="text" class="form-control" ng-model="Alias" placeholder="Alias" maxlength="50" required>
  </div>

  <button type="submit" class="btn btn-info" ng-click="update()">Submit</button>
  <button type="submit" class="btn btn-info" data-dismiss="modal">Cancel</button>
</form>

我的控制器js是。

$scope.update= function () {
    alert($scope.userForm.Name.$valid);
    if ($scope.userForm.Name.$valid) {
        alert("Entry added");
    }
}

显示小对话框,表示此字段是必需的。我不想要这个弹出窗口。为什么跨度部分没有显示?

2 个答案:

答案 0 :(得分:3)

要做到这一点,关键是使用name和所有输入中的<form>属性。 按照这种方式,angularjs将创建一个表单实例,您可以在其中访问所有字段,如myForm.myInput.$invalid

例如:

<form name="myForm" novalidate>     
    <label>My Input:</label>
    <input type="text" name="myInput" ng-model="myInput" required>
    <span ng-show="myForm.myInput.$dirty && myForm.myInput.$invalid">My Input is invalid.</span>
</form>

检查角度docs

答案 1 :(得分:1)

HTML

<div ng-app="myApp">
<form name="cutome_form" ng-submit="submitForm()" novalidate>

   <input type="text" name="name" class="form-control" ng-model="Name" placeholder="Name" maxlength="50" required>
                              <div ng-show="cutome_form.name.$dirty && cutome_form.name.$invalid">
                                 <span class="error" ng-show="cutome_form.name.$error.required">The field is required.</span>
                              </div>

                 <div class="form-group">
                            <label for="pwd">Alias:</label>
                            <input type="text" name="alias" class="form-control" ng-model="Alias" placeholder="Alias" maxlength="50" required>
                        </div>
    <div ng-show="cutome_form.alias.$dirty && cutome_form.alias.$invalid">
      <span class="error" ng-show="cutome_form.alias.$error.required">The field is required.</span>
    </div>

  <button type="submit" ng-disabled="cutome_form.$invalid">Submit All</button>
</form>
</div>

指令

  .directive('ngModel', function() {
    return {
        require: 'ngModel',
        link: function(scope, elem, attr, ngModel) {
            elem.on('blur', function() {
                ngModel.$dirty = true;
                scope.$apply();
            });

            ngModel.$viewChangeListeners.push(function() {
                ngModel.$dirty = false;
            });

            scope.$on('$destroy', function() {
                elem.off('blur');
            });
        }
    }
});