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

时间:2018-10-24 06:17:43

标签: angularjs angularjs-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]};
};  

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

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

但是它什么都不打印。如何在带有动态变量的ng-repeat内打印作用域数组?

1 个答案:

答案 0 :(得分:2)

首先,您似乎正在使用$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