When it comes to validating a form in Angular, I usually use the ng-submit
directive like this:
<form name="formName" ng-submit="formName.$valid && submitForm()"></form>
This method works well for forms with predefined names that I set during form creation. However, I am currently facing a situation where I need to dynamically generate multiple forms based on a list of objects. Each form has its name generated dynamically.
So how can I validate these dynamically named forms before executing the submitForm()
function?
You can check out a simplified version of the issue in this jsfiddle: http://jsfiddle.net/flyingL123/ub6wLewc/1/
The main question is, how do I access the dynamically generated form name for validation? Here is the code snippet from the fiddle:
var app = angular.module('app', []);
app.controller("AppController", ['$scope', function($scope) {
$scope.forms = [{
id: 1,
value: "val1"
}, {
id: 2,
value: "val2"
}, {
id: 3,
value: "val3"
}];
$scope.submitForm = function() {
alert('submitted');
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div id="app" ng-app="app" ng-controller="AppController">
<div class="formWrapper" ng-repeat="form in forms">
<form name="{{ 'form' + form.id }}" ng-submit="submitForm()" novalidate>
<input ng-model="form.value" required />
<button type="submit">Submit</button>
</form>
</div>
</div>