Exploring the power of Angular's ng-repeat to generate hierarchical lists

I am looking to display a structured list of layers and sublayers by looping through an object using 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>

Currently, only the Layers are being listed. It appears that ng-repeat is not cascading down to the next <ul>. I attempted placing ng-repeat inside the <ul> tag but it displayed the entire list instead of just the desired sub-layers.

This is how I envision the final output:

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 №1

Here is the solution you are seeking:

To enhance the output, consider redesigning your object by incorporating sublayers within layers. This approach allows for easy display of sub layers in the 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to utilize the three.js texture loader within a JavaScript worker environment

I'm currently experimenting with three.js to load textures. Here is the snippet from my main.js file: const worker = new Worker('../workers/worker.js', { type: 'module' }); And this is a simplified version of worker.js that ...

Select a file and upload an image promptly after it is chosen

Is there a way to automatically upload an image once a user selects a file in their browser? Similar to how it works on Facebook, where users can choose a file for their cover or profile image and then the upload process begins. Currently, all I have is ...

Tips for sending and retrieving parameters using the POST technique

Currently, I am in the process of building a user authentication form for my website using Javascript. I am utilizing Vue JS on the client-side and NodeJS with ExpressJS on the server-side. For the server-side functionality, I have implemented the followi ...

Puppeteer with Typescript: Encountering issues during the transpilation process

The issue stems from the fact that I am unable to use Javascript directly due to Firebase Functions Node.JS version lacking support for Async/Await. As a workaround, I have converted the code into Typescript and am currently attempting to transpile it to c ...

How can you access the URL of a resource action in Angular?

In my Angular application, I have created a resource named 'Files' with the following definition: app.factory('Files', function($resource) { return $resource('/api/accounts/:account_id/sites/:site_id/files/:file_id'); }); ...

How can I filter an array to retain only the initial 5 characters of every element?

I need help using the .map function to transform this array so that only the first 5 characters are displayed, like "01:00", "02:00"? This is the array: ["01:00:00 AM", "02:00:00 AM", "03:00:00 AM", "04:00:00 AM", "05:00:00 AM", "06:00:00 AM", "07:00:00 ...

Utilizing Firebase in place of .json files for the AngularJS Phonecat application

I am currently exploring firebase and attempting to retrieve data using this service from firebase instead of json files. However, I have encountered some challenges in getting it to function properly. This is inspired by the angularjs phonecat example .f ...

Achieving the highest ranking for Kendo chart series item labels

Currently, I am working with a Kendo column chart that has multiple series per category. My goal is to position Kendo chart series item labels on top regardless of their value. By default, these labels are placed at the end of each chart item, appearing o ...

tips for using Node Mailer to send emails without using SMTP

Currently, I am facing an issue with sending emails through nodemailer. Although I have successfully used my gmail account for this purpose in the past, I now wish to switch to using my business email to communicate with clients on a regular basis. The cu ...

Tips for displaying a close icon after completing a file upload

I need to implement a feature where once a user uploads a file, a cross sign should be enabled on the file. I attempted to use javascript for this functionality, but it seems to not be working as expected. There are more than 8-10 different file types that ...

Removing the hash symbol in Angular: A step-by-step guide

My experience with AngularJS is new, and I am currently working on removing the # from the URLs without utilizing NODE or Express. The project is being hosted locally on MAMP, with index.html acting as the main entry point. Within the structure, there are ...

Troubleshooting the issue with default useAsDefault routing in Angular 2

I have implemented Angular 2 for routing and Node for local hosting. However, I encountered an issue where using 'useAsDefault:true' for my route caused the nav bar links to stop functioning properly. The URL would redirect to http://localhost/ ...

Which free and publicly accessible JSON image API is available for testing JSON requests?

Recently, I've been experimenting with AngularJS and am eager to incorporate some images using free APIs. While exploring options, I came across Flickr but was discouraged by the registration requirement for app usage. I am seeking a more accessible s ...

Javascript 'break' statement is always executed

It seems like I'm overlooking a very basic concept here. Why isn't my code reaching the else statement? The issue might be related to the break statement. It's likely something simple that I am missing. Code Snippet: <button onclick="yo ...

Whenever text is present, the sides of my box model, constructed using HTML5 and CSS3, are always pushed downward

When I add extra text to the body of my homepage, it causes a distortion and pushes down the sidebar and advertising boxes on the side. I'm working on this project for class and even though I've asked my teacher for help, she says the code is fin ...

Ways to store Token in Browser Cache?

I am currently developing a login system for an application at my school. I have successfully implemented user registration, which is saved to my Azure DocumentDB. However, when trying to log in with the user, the token does not get saved so that I can acc ...

Making an Http Get request in Angular 2 by passing a JSON object

How can I make an HTTP GET request and send a JSON object along with it? Here is the JSON object: {{firstname:"Peter", lastname:"Test"} I want to pass this object in the HTTP request to receive a list of matched persons. Is this possible? The example o ...

Encountering NodeJS server issues with 505/404 errors while fetching partials

I am currently working on an application built using the M.E.A.N stack. For routing, I have implemented Angular Ui Router. However, I am encountering difficulties in correctly routing partials. The link for the main view is functioning properly with the ...

Having trouble deciphering the JSON data structure in JavaScript

How can values be passed back to a form that was submitted to the server using Ajax? In this view (shown below), a simple data structure is returned for testing purposes: def detail(request, widget_id): widget = get_object_or_404(Widget, pk=widget_i ...

Tips for creating a Carousel with more than three images using Bootstrap

Recently, I attempted to enhance my Carousel in Bootstrap by adding more images. Initially, I inserted the code snippet below within the ordered list with the class "carousel-indicators." <li data-target="#carouselExampleCaptions" data-slide-to=" ...