2014-12-05 26 views
0

我在表格內有一個表單。表單驗證不能與angularJS一起工作

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

當輸入欄位爲空時,應顯示需要品牌名稱。但它不工作。

有人可以幫助我這個。

回答

0

你可以做,使用指令: - 舉一個例子:

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