6

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

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

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

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

Here's a jsfiddle of the simplified problem: http://jsfiddle.net/flyingL123/ub6wLewc/1/

My question is, how can I access the name of the form in order to validate it? Here is the code 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>
user2314737
  • 27,088
  • 20
  • 102
  • 114
flyingL123
  • 7,686
  • 11
  • 66
  • 135

1 Answers1

8

You can always use this to access the scope 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>
Blackhole
  • 20,129
  • 7
  • 70
  • 68