Robert Robert - 10 months ago 60
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" }


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

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

This is the result I'm trying to get:

- Layer Base Maps
- Sub Layer Open Street Map

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

Answer Source

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',[])
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) {
  		this[count].sub = []; //define sub layer inside layer
  		this[count-1].sub.push(value); //assign sub layer inside layer
}, newList);
$scope.lyrslist = newList;
<script src=""></script>

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