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

标签 javascript angularjs angularjs-scope angularjs-ng-repeat

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

以下变量在我的 $scope 中定义:error_question1 , error_question2 , error_question3

我在 ng-repeat 中有以下内容,我正在尝试使用 ng-repeat 的 $index 将跨度的值分配给 $scope 中的相应变量。

我可以通过直接定位变量来让它工作,但显然它会像我的 ng-repeat 中的每个项目一样重复:

<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]}},您基本上是在说“将位于 $index + 1 位置的项目给我error_question 数组”。这不是你想要的。

尝试使用不同的方法。不要让所有 error_question1、error_question2、... error_questionX 都在 $scope 中 float ,而是使用一个对象来封装错误。像这样:

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

这样您就可以像这样在 HTML 中使用它:

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

Plunker

关于javascript - Angular 从 ng-repeat 中的 $scope 获取动态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25669509/

相关文章:

javascript - 无法使用 Rails 在 Ajax 请求中通过 url 传递参数

javascript - react 映射函数未返回的无状态组件

javascript - Protractor 给出错误的选择器错误

mysql - PHP MySQL 数据到 AngularJS

javascript - Angular 将特定数据检索到 $scope 变量中不起作用

javascript - 在 Controller 中使用 `this` 作用域时使用 $scope.$watch

javascript - 使用 d3 加载 csv 文件后范围未更新

javascript - Google map (ngmap 指令)- 未捕获的 TypeError : Cannot read property 'x' of undefined

javascript - 在 CKEditor5 中插入自定义元素

javascript - Angular : Watch collection on field change and make a calculations