FelixM FelixM - 1 year ago 84
AngularJS Question

How to use ng-messages within repeated md-input-container

With Angular 1.5.5 and Angular-Material 1.0.9 I have created a HTML form like this with a repeated

element. I want to use
for the error messages. The problem I have is that when I enter for example
, the correct error message is shown in a tooltip, but not below the input element. The issue seems to be that the
attribute does not support interpolation like the
attribute. I could put a variable into the
which contains the correct name, but I am not happy with that option because then the
is defined in the HTML template and the JavaScript controller. Is there a way to do this more cleanly?

<form name="form">
<md-input-container ng-repeat="product in purchase.products">
<input type="number" min="0" max="9999" ng-model="product.quantity"
<div ng-messages="form.product[$index].quantity.$error" md-auto-hide="false">
<div ng-message="min">Please enter 0 or more</div>
<div ng-message="max">Please enter 9999 or less</div>

To be extra clear: In the rendered DOM, there is
<input name="product[0].quantity"
does not change and
is not evaluated. I guess I would need an expression that evaluates to

Answer Source

Change your name property to:

<input type="number" min="0" max="9999" required ng-model="product.quantity" name="product_{{$index}}">

And your ngMessages to:

<div ng-messages="form['product_' + $index].$error">

Now it should work.