Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ngMessages can't bind to $index expression

I am building an Angular form that needs repeatable form elements inside an ngRepeat.

<form name="form">
    <div ng-repeat="x in [1,2,3,4]">
      <input name="something_{{$index}}" ng-model="hi" required>
      <div ng-messages="form.something_{{$index}}.$error">
        <ng-message="required">This is required</ng-message>
      </div>
    </div>
    <pre>{{form | json: 4}}</pre>
  </form>

Angular now supports dynamically declared input names so that you don't have to do something like:

<div ng-repeat="x in [1,2,3,4] ng-form="repeated-form"></div>

And you can use {{$index}} inside the ngRepeat to declare items dynamically. But this doesn't seem to work with ngMessages, which throws an error when I try to bind the index into it.

i.e. this:

<div ng-messages="form.something_{{$index}}.$error">

throws this:

Error: [$parse:syntax] Syntax Error: Token '{' is an unexpected token at column 16 of the expression [form.something_{{$index}}.$error] starting at [{{$index}}.$error].

How can we dynamically declare which property on the form to watch, if ng-messages can't watch the form value that is declared with its {{$index}}?

PLNKR: http://plnkr.co/edit/4oOasbtffTgKqmxcppUG?p=preview (check console)

like image 590
nikk wong Avatar asked Aug 06 '15 18:08

nikk wong


2 Answers

ng-messages="form['something_' + $index].$error"

Should work. I generally wouldn't put {{ }} in any of the ng directives because most of the ng directives execute with priority level 0 (including the {{ }} directive, ngBind). Also, the ng directives all use $evaluate on their argument, so they look at variable values in the scope by default.

Priority 0 for multiple directives on the same element means that Angular can't guarantee which directive will be applied first. Because of that, it is generally best to avoid using ngDirectives together as behavior can vary. ngIf is an exception as it executes with priority 600 (which is why directives aren't evaluated for an ng-if element not currently in the DOM no matter what).

like image 116
Tahsis Claus Avatar answered Oct 23 '22 14:10

Tahsis Claus


    <div ng-repeat="x in [0,1,2,3]">
      <input name="something_{{$index}}" ng-model="hi" required>
      <div ng-messages="form['something_' + $index].$error">
        <ng-message="required">This is required</ng-message>
      </div>
    </div>

http://plnkr.co/edit/k5nzkpkJwSuf5dvlMMZi?p=preview

like image 33
Deblaton Jean-Philippe Avatar answered Oct 23 '22 12:10

Deblaton Jean-Philippe