Robert Robert - 1 month ago 13
AngularJS Question

Using Angular ng-repeat to create nested list

I want to create a list of layers and nested list of sublayers for each layer by iterating this object with ng-repeat.

var lyrslist = [
{ layername: "Base Maps", layertype: "layer" },
{ layername: "Open Street Map", layertype: "sublayer" },
{ layername: "Designated Sites", layertype: "layer" },
{ layername: "Ancient Woodlands", layertype: "sublayer" },
{ layername: "Conservation Areas", layertype: "sublayer" },
{ layername: "Listed Buildings", layertype: "sublayer" }
];


HTML



<h5>Layers</h5>
<ul ng-repeat="lyr in lyrslist">
<li ng-if="lyr.layertype === 'layer'" >
Layer {{lyr.layername}}
<ul>
<li ng-if="lyr.layertype === 'sublayer'">
Sub Layer {{lyr.layername}}
</li>
</ul>
</li>
</ul>


The result is that only the Layers are being listed. It seems that
ng-repeat
doesn't cascade down to the next
<ul>
. I tried putting
ng-repeat
inside the
<ul>
tag but that just the whole list instead of the just the required sub-layers.

This is the result I'm trying to get:

Layers
- Layer Base Maps
- Sub Layer Open Street Map

- Layer Designated Sites
- Sub Layer Ancient Woodlands
- Sub Layer Conservation Areas
- Sub Layer Listed Buildings

Answer

I think you are looking for this:

You have to redesign your object for better output. I have include sublayer inside layer. That's why you can easily display sub layer in view.

var app = angular.module('app',[])
app.controller('ctrl',function($scope){
var lyrslist = [{ layername:"Base Maps",  layertype:"layer"},  {layername:"Open Street Map",  layertype:"sublayer"}, { layername:"Designated Sites",  layertype:"layer"}, { layername:"Ancient Woodlands",  layertype:"sublayer"}, { layername:"Conservation Areas",  layertype:"sublayer"}, { layername:"Listed Buildings",  layertype:"sublayer"}];

var newList = []; var count = 0; 
angular.forEach(lyrslist, function(value, key) {
	if(value.layertype=='layer'){
  		this.push(value);
  		this[count].sub = []; //define sub layer inside layer
  		count++;
  	}else{
  		this[count-1].sub.push(value); //assign sub layer inside layer
  	}
}, newList);
//console.log(newList);
$scope.lyrslist = newList;
  
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
        <ul>
            <li ng-repeat="lyr in lyrslist">
                Layer: {{lyr.layername}}
              <ul>
                  <li ng-repeat="sublyr in lyr.sub"> 
                     SubLayer: {{sublyr.layername}}
                 </li>
              </ul>
            </li>
    </ul>
</div>