在ng-model中使用$ index的Angular

时间:2015-01-22 19:02:06

标签: javascript html angularjs angularjs-ng-model

我有以下循环,我每次都要尝试根据数组索引递增几个字段。

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

我想做类似的事情&#34;

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

Angular虽然没有渲染这个值?在mg模型领域中添加这种逻辑的最佳方法是什么?

1 个答案:

答案 0 :(得分:13)

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

即你的控制器:

$scope.interpretation = {};

并在您的视图中将其用作:

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

<强>演示

&#13;
&#13;
angular.module('app', []).controller('ctrl', function($scope) {
  $scope.interpretation = {};
  $scope.actions = {};
});
&#13;
<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>
&#13;
&#13;
&#13;