【问题标题】:Angular using $index in ng-modelAngular 在 ng-model 中使用 $index
【发布时间】:2015-01-22 19:02:06
【问题描述】:

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

<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 字段中添加这种逻辑的最佳方法是什么?

【问题讨论】:

标签: javascript html angularjs angularjs-ng-model


【解决方案1】:

在使用 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>

【讨论】:

  • 我似乎无法将括号符号解析为值。 ng-model="interpretation[$index + 1]" 呈现在 html 以及我尝试过的其他范围值中。
  • 为我工作。你使用的是什么版本的角度?
  • 查看演示内嵌编辑到答案中。好吧,您需要在控制器中事先定义对象,这样您就不会更新子范围内的属性
  • 它似乎仍然不起作用。 chrome 检查器中的 sn-p 代码仍显示未插值的 {{}} 符号。我正在使用角度 1.3
  • 你说的是value属性吗?如果是这样 #1) 纯 html 中的 value 属性仅用于指定默认值,#2) 只需输入 &lt;textarea&gt;&lt;/textarea&gt; 并输入并查看检查,您将看不到任何值或任何内容。更新的是 value 属性而不是属性 #3) 使用 Angular 时,您不必担心 DOM,您只需担心 ng-model 和视图模型绑定,让 Angular 管理 DOM,但它需要,不是重点做角度的方式
猜你喜欢
  • 2013-06-27
  • 1970-01-01
  • 2017-02-11
  • 1970-01-01
  • 2016-06-09
  • 2017-04-02
  • 2016-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多