0

I'm dynamically creating forms with ng-repeat and they have some validation attributes (simplified version):

<div class="row" ng-repeat="defect in model.defects">
    <form name="form_{{defect.id}}" novalidate>
      <input ng-model="defect.name" required/>
      <input type="submit" ng-click="saveDefect(defect)"/>
     </form>
</div>

Basically what I want to do is this:

$scope.saveDefect = function (defect) {
         if ($scope.<how to get the form name here>.$invalid) {
             return;
         }
}

Since the form name has been created dynamically with an id how do I access it? Other ways of doing the same are also welcome ofcourse :)

3
  • didn't you bind the form name to any variable??? Commented Oct 27, 2015 at 15:06
  • @MohammadJavadSeyyedi what do you mean? Commented Oct 27, 2015 at 15:13
  • @Elger I added a code snipper to my answer to better explain my solution, please tell me if it's what you wanted Commented Oct 27, 2015 at 15:23

1 Answer 1

2

You can use the bracket notation to access it :

$scope["form_"+defect.id]

What I advise you to do is :

var app = angular.module("App", []);
app.controller("Ctrl", function($scope) {
  $scope.forms = {};
  $scope.list = [{id: 1}, {id: 2}];
  
  $scope.save = function(item) {
    if ($scope.forms["form_" + item.id].$invalid) {
      alert("error on form_" + item.id);
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="App" ng-controller="Ctrl">
  <div class="row" ng-repeat="item in list">
    <form name="forms.form_{{item.id}}" novalidate>
      <input ng-model="item.name" required/>
      <input type="submit" ng-click="save(item)" />
    </form>
  </div>
</body>

Sign up to request clarification or add additional context in comments.

1 Comment

Putting the forms in an object makes it work. Now you show me it makes me realize the repeater creates new scopes, so otherwise it won't work. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.