【问题标题】:Form validation Not working with angularJS表单验证不适用于 angularJS
【发布时间】:2014-12-05 15:05:45
【问题描述】:

我在表格中有一个表格。

    <table class='table table-bordered'>
        <caption>ADD NEW BRAND</caption>

        <tbody>
            <form ng-app="" class="form-horizontal" role="form" name="myForm">

                <div class="form-group">
                    <TR>
                        <TD>Brand Name</TD>

                        <TD>
                            <input type="text" class="form-control" name="name" ng-model="newbrand.Name" placeholder="Enter Brand Name" required>
                            <span style="color:red" ng-show="myForm.name.$dirty && myForm.name.$invalid">
                                <span ng-show="myForm.name.$error.required">Brand Name is required.</span>
                            </span>
                        </TD>
                    </TR>
                </div>
            </form>
        </tbody>
    </table>

当输入字段为空时,应指示需要品牌名称。但它不起作用。

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: angularjs forms


    【解决方案1】:

    您可以使用指令来做到这一点:- 举个例子:

    html
    
      <body ng-controller="MainCtrl">
        <form novalidate class="person" name="personForm" test-directive validation="submitPerson" ng-submit="submitForm(personForm)">
          <h3>Person form</h3>
          <input type="text" required name="first-name" ng-model="person.firstName" ng-class="{'valid':personValid}" />
          <input type="submit" value="post" />
        </form>
      </body>
    

    控制器和指令

    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope) {
      $scope.person = {
        firstName: 'Clem'
      };
    
    
      $scope.submitPerson = function(form, element) {
        console.log("Person validation here!")
        if(form.$valid) {
          $scope.personValid = true;
        }
        else {
          $scope.personValid = false;
        }
      };
    
    });
    
    app.directive('testDirective', function ($compile) {
      return {
        restrict: 'A',
        scope: true,
        link: function (scope, ele, attrs) {
          scope.submitForm = function(form) {
            eval("var fn = scope." + attrs.validation);
            fn(form, ele);
          }
        }
      };
    })
    

    信用:- Form validation in angular

    【讨论】:

      猜你喜欢
      • 2016-12-13
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 2021-11-10
      • 2016-06-04
      • 1970-01-01
      • 2018-10-01
      • 2019-08-29
      相关资源
      最近更新 更多