如何在重复的 md-input-container 中使用 ng-messages

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

使用 Angular 1.5.5 和 Angular-Material 1.0.9 我创建了一个 HTML 形式,其中包含一个重复的 input 元素.我想使用 ngMessages 作为错误信息。我遇到的问题是,当我输入例如 -1 时,正确的错误消息会显示在工具提示中,但不会显示在输入元素下方。问题似乎是 ng-messages 属性不像 inputname 属性那样支持插值。我可以将一个变量放入包含正确名称的 $scope 中,但我对该选项不满意,因为 inputname 是在 HTML 中定义的模板和 JavaScript 控制器。有没有办法更干净地做到这一点?

<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>

要特别清楚:在呈现的 DOM 中,有 <input name="product[0].quantity"ng-messages 没有改变,并且 $index 没有被评估。我想我需要一个计算结果为 "product[0].quantity".

的表达式

将您的 name 属性 更改为:

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

你的 ngMessages 到:

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

现在应该可以了。