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