简体   繁体   English

角从ng-repeat中的$ scope获取动态变量

[英]Angular get dynamic variable from $scope inside ng-repeat

I'm unable to output a variable within my $scope inside an ng-repeat 我无法在ng-repeat的$ scope中输出变量

The following variables are defined inside my $scope: error_question1 , error_question2 , error_question3 我的$ scope中定义了以下变量: error_question1error_question2error_question3

I have the below inside an ng-repeat and I'm trying to assign the span's value to the corresponding variable within my $scope using the ng-repeat's $index. 我在ng-repeat中包含以下内容,并尝试使用ng-repeat的$ index将范围的值分配给$ scope中的相应变量。

I can get this working by directly targeting the variable but obviously it duplicates for every item in my ng-repeat like so: 我可以通过直接定位变量来使它工作,但是很明显,它对我的​​ng-repeat中的每个项目都重复如下:

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

However, the way I imagine it working does not work: 但是,我认为它无法正常工作:

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

The [$index+1] appears to be breaking it? [$ index + 1]似乎被破坏了吗?

Note that by doing {{error_question[$index + 1]}} you are basically saying "get me the item at the position $index + 1 of the error_question array". 请注意,通过执行{{error_question[$index + 1]}}您基本上是在说“让我在error_question数组的$index + 1位置获得项目”。 That's not what you want. 那不是你想要的。

Try using a different approach. 尝试使用其他方法。 Instead of having all the error_question1, error_question2, ... error_questionX floating around in the $scope , use an object to encapsulate the errors. 而不是在$scope浮动所有的error_question1,error_question2,... error_questionX ,请使用一个对象来封装错误。 Like this: 像这样:

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

This way you can use it in the HTML like this: 这样,您可以像下面这样在HTML中使用它:

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

Plunker 柱塞

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM