如何在 ng-repeat 中传递动态变量

How to pass dynamic variable inside ng-repeat

我有一个数组,其名称和我函数中的当前 ID:

$scope.expand = function(hodid, supid, leader_id, staff_id, importance){
  var tr_id = 'expand_tree_'+hodid;

在控制台输出中,它将如下所示:expand_tree_1000321 这就是我的数组最终的样子:

  $scope[tr_id] = {firstLevel:[$scope.firstLevelLst], secondLevel:[$scope.secondLevelLst], thirdLevel:[data_third]};
};  

现在我想在 ng-repeat 中打印此 $scope[tr_id],其中 tAttrs.treeid 是所选用户的 ID:

<div  ng-repeat="first in ['expand_tree_'+tAttrs.treeid].firstLevel['0']">
  {{first.username}}
</div>

但是它不打印任何东西。如何使用动态变量在 ng-repeat 内打印作用域数组?

首先,您似乎正在使用 $scope 作为您的数据对象。出于几个原因,这并不好。在范围内使用一个对象,例如:

$scope.data = {};

并像这样存储数据:

$scope.data[tr_id] = {
    firstLevel: [$scope.firstLevelLst],
    secondLevel: [$scope.secondLevelLst],
    thirdLevel: [data_third]
};

但是不要将属性包装在数组中,因为它们已经是数组:

$scope.data[tr_id] = {
    firstLevel: $scope.firstLevelLst,
    secondLevel: $scope.secondLevelLst,
    thirdLevel: data_third
};

然后你可以循环 first 像:

<div ng-repeat="first in data['expand_tree_' + tAttrs.treeid].firstLevel">
    {{first.username}}<br />
</div>

这是一个Working Fiddle