javascript Angular 在 ng-model 中使用 $index

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28096653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:24:04  来源:igfitidea点击:

Angular using $index in ng-model

javascripthtmlangularjsangularjs-ng-model

提问by byrdr

I have the following loop in which I'm trying to increment several fields based on the array index each time through the loop.

我有以下循环,我试图在每次循环时根据数组索引增加几个字段。

<div class="individualwrapper" ng-repeat="n in [] | range:4">
  <div class="iconimage"></div>
  <div class="icontext">
    <p>Imagine that you are in a health care facility.</p> 
    <p>Exactly what do you think this symbol means?</p>
    <textarea type="text" name="interpretation_1" ng-model="interpretation_1" ng-required="true"></textarea>
    <p>What action you would take in response to this symbol?</p>
    <textarea type="text" name="action_1" ng-model="action_1" ng-required="true"></textarea>  
  </div>
</div>

I'd like to do something similar to this"

我想做类似的事情”

ng-model="interpretation_{{$index + 1}}"

Angular is not rendering that value though? What would be the best way to go about adding this kind of logic in the mg-model field?

Angular 没有渲染那个值?在 mg-model 字段中添加这种逻辑的最佳方法是什么?

回答by PSL

It becomes an invalid expression with the usage of interpolation with ng-model expression. You need to provide a property name there. Instead you can use an object and use bracket notation.

使用带有 ng-model 表达式的插值,它会变成无效的表达式。您需要在那里提供属性名称。相反,您可以使用对象并使用括号表示法。

i.e in your controller:

即在您的控制器中:

$scope.interpretation = {};

and in your view use it as:

并在您看来将其用作:

ng-model="interpretation[$index + 1]"

Demo

演示

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.interpretation = {};
  $scope.actions = {};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  {{interpretation}} {{actions}}
  <div class="individualwrapper" ng-repeat="n in [1,2,3,4]">
    <div class="iconimage">
    </div>
    <div class="icontext">
      <p>Imagine that you are in a health care facility.</p>
      <p>Exactly what do you think this symbol means?</p>
      <textarea type="text" ng-attr-name="interpretation{{$index + 1}}" ng-model="interpretation[$index+1]" ng-required="true"></textarea>
      <p>What action you would take in response to this symbol?</p>
      <textarea type="text" name="action{{$index + 1}}" ng-model="actions[$index+1]" ng-required="true"></textarea>
    </div>
  </div>
</div>