Angular submit form with dynamic name

Typically, to check the form in Angular, I would use something like this in the ng-submit directive:

 <form name="formName" ng-submit="formName.$valid && submitForm()"></form> 

This works great when a form has a name that I set when creating the form. However, in my current situation, I am trying to create several forms based on a list of objects. In this case, each form has a name that is determined on the fly.

When a user submits one of these forms, how can I check it before running the submitForm() function for this form?

Here's the jsfiddle simplified task: http://jsfiddle.net/flyingL123/ub6wLewc/1/

My question is, how can I access the form name to validate it? Here is the code from the script:

 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> 
+5
source share
1 answer

You can always use this to access the area in your templates.

 {{this.foo === foo}} <!-- This will always show "true" --> 

Therefore, you can simply use this[myDynamicFormName] to access the form:

 <form name="{{'form' + form.id}}" ng-submit="this['form' + form.id].$valid && submitForm()"></form> 
+7
source

Source: https://habr.com/ru/post/1203742/


All Articles