10

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

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

我想做类似的事情”

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

Angular 没有呈现该值吗?在 mg-model 字段中添加这种逻辑的最佳方法是什么?

4

1 回答 1

14

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

即在您的控制器中:

$scope.interpretation = {};

在您看来,将其用作:

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

演示

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>

于 2015-01-22T19:07:02.480 回答