Angular从ng repeat内的$scope获取动态变量

Angular get dynamic variable from $scope inside ng-repeat

本文关键字:scope 获取 动态 变量 内的 ng repeat Angular      更新时间:2023-09-26

我无法在ng-reeat 中输出$scope内的变量

以下变量在我的$范围内定义:error_question1error_question2error _question3

我在一个ng repeat中有以下内容,我正试图使用ng repeat的$索引将span的值分配给我的$范围内的相应变量。

我可以通过直接针对变量来实现这一点,但很明显,它对我的ng中的每个项目都是重复的,就像这样:

<span class="help-block" ng-show="error_question{{$index + 1}}">{{error_question2}}</span>

然而,我认为它的工作方式不起作用:

<span class="help-block" ng-show="error_question{{$index + 1}}">{{error_question[$index + 1]}}</span>

[$index+1]似乎正在破坏它?

注意,通过执行{{error_question[$index + 1]}},您基本上是在说"在error_question数组的$index + 1位置为我获取项目"。这不是你想要的。

尝试使用不同的方法。而不是所有的error_question1、error_question 2。。。error_questionX$scope中浮动,使用对象封装错误。像这样:

$scope.errors = {
  question1: ...,
  question2: ...,
  question3: ...,
  ...
};

通过这种方式,你可以在HTML中使用它,如下所示:

<span class="help-block" ng-show="errors.question{{$index + 1}}">{{errors['question' + ($index + 1)]}}</span>

Plunker