FelixM FelixM - 4 months ago 27
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

input
element. I want to use
ngMessages
for the error messages. The problem I have is that when I enter for example
-1
, the correct error message is shown in a tooltip, but not below the input element. The issue seems to be that the
ng-messages
attribute does not support interpolation like the
input
's
name
attribute. I could put a variable into the
$scope
which contains the correct name, but I am not happy with that option because then the
input
's
name
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"
name="product[{{$index}}].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>
</div>
</md-input-container>
</form>


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

Answer

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.

Comments