Search code examples
javascripthtmlangularjsangularjs-ng-repeat

How to pass dynamic variable inside ng-repeat


I have an array which has name with current id inside my function:

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

In console output it will look like this: expand_tree_1000321 That's how my array will look in the end:

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

Now I want to print this $scope[tr_id] inside ng-repeat where tAttrs.treeid is id of the selected user:

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

But it doesnt print anything. How can I print scope array inside ng-repeat with dynamic variable?


Solution

  • First, it looks like you are using $scope as your data object. This is not good for a couple reasons. Use an object on the scope instead like:

    $scope.data = {};
    

    And store the data like:

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

    But don't wrap the properties in an array, since they are already arrays:

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

    Then you can loop through first like:

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

    Here is a Working Fiddle