angular.js form validation in controller

坚强是说给别人听的谎言 提交于 2021-01-28 04:30:59

问题


I got this form:

<form ng-controller="SomeCtrl as some" name="product[[product.id]]" ng-submit="some.addToCart(something, product[[product.id]].$valid)" novalidate></form>

Then html looks like:

<form ng-controller="SomeCtrl as some" name="product1" ng-submit="some.addToCart(something, product1.$valid)" novalidate=""></form>

Controller:

this.addToCart = function(something, isValid) {
    console.log(isValid);
}

isValid is always undefined. How to detect if form is valid in controller?


回答1:


Demo You don't want to use ng-submit if you want to do your own validation in the controller because it will block the submission of the form if it is invalid.

Just use a regular button with a function in ng-click that checks the condition of the form.

Controller:

  $scope.submit = function() {
    console.log($scope.myForm.$valid)
  }

HTML

<form name="myForm">
  <input ng-model="myForm.text" type="text" required />
  <button ng-click="submit()">Submit</button>
</form>


来源:https://stackoverflow.com/questions/29929961/angular-js-form-validation-in-controller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!