3
votes

Normally, with a form and input fields, the form controller is published into the related scope under the form name attribute. And, the NgModelController is published under the input name attribute. So for an input field with an ngModel directive, the NgModelController for the input field can be retrieved like $scope.myFormName.myInputFieldName

The question is how to do the same thing (get the NgModelController) for input fields inside the ngRepeat directive?

I would like to name the input fields using $index as part of the name so each template instance is uniquely named. This renders OK, so

<input name="foo_{{$index}}" ...

renders the instance with $index == 3 to

<input name="foo_3" ...

But trying to get the ngModelController via the published names does not work (it's undefined), e.g.:

$scope.myFormName.foo_3

A plunker showing this is here: http://plnkr.co/edit/jYDhZfgC3Ud0fXUuP7To?p=preview

It shows successfully getting the ngModelController for a 'plain' input element and calling $setValidity, and also shows failing to get the ngModelController for an input element inside an ngRepeat directive.

Copied the relevant section of code from the plunker below:

<div ng-repeat="element in elements">
  <div ng-class="{error: form['foo_{{$index}}'].$invalid}">
    <input name="foo_{{$index}}" ng-model="element.a" type="number">
    <span ng-show="form['foo_{{$index}}'].$error.bar">ngRepeat bar invalid</span>
  </div>
</div>
{{form.foo_0.$setValidity('bar', false)}}
2
I would guess the problem is that ng-repeat creates a new scope and that you cannot simple access the child scope: similar to this answer here: stackoverflow.com/questions/14491433/… Sorry I don't have a nice idea how to change that other than writing a custom directive at the moment :/F Lekschas

2 Answers

2
votes

@Flek is correct that the new child scopes that ng-repeat creates are the root of the problem here. Since browsers do not allow nesting of <form> elements, ngForm must be used when nesting forms, or when you want to do form validation inside ngRepeat.

See Pawel's answer on the google group thread, which shows how to use ng-form to create inner forms, and/or @blesh's SO answer.

1
votes

If i understand your question correctly, you are trying to have access to the form elements created inside the ng-repeat.

Please have a look at this fiddle http://jsfiddle.net/EF5Jp/. Inside the button click handler you will have the access to the element with id myForm.foo_2. You can notice that the element is retrieved by myForm.foo_2 and not $scope.myForm.foo_2. Second thing is, changing the value using its scope and not using its value property like angular.element(element).scope().foo = 6;.