Traversing a JavaScript object's array using AngularJS

As someone who is brand new to coding, I am embarking on the journey of building a basic website using AngularJS. However, I've hit a roadblock when it comes to looping through an object array in a controller and displaying each item in a directive template. My aim is to showcase each string in the array as a separate list item within the template.

    $scope.items = [
    {
     list: ["1", "2", "3"],
     name: "whatever"
    },
    {
     list: ["4", "5", "6", "7", "8"],
     name: "whatever2"
    }]

In my directive template, I have attempted the following:

    <h1>{{ directive.name }}</h1>
    <ul id= "items"></ul>
    <script>
            for (var i = 0; i < directive.list[].length; i++) {
                  document.getElementById("items").innerHTML = 
                   "<li>{{" + directive.list[i] + "}}</li>";
            };
    </script>

Although the 'name' object displays correctly in index.html using the template, the 'list' object fails to output the array items. Despite my best efforts and troubleshooting, I can't seem to crack this issue. Any guidance would be greatly appreciated. This is all very new to me, and I'm still getting familiar with the terminology and concepts. Thank you in advance for any help!

Answer №1

Check out this awesome example:

<div ng-repeat="i in items">
   <h1>{{ i.name }}</h1>
   <ul>
     <li ng-repeat="item in i.list">{{i}} </li>
   </ul>
</div>

Here's a brief explanation:

The code loops through each item in the array with <div ng-repeat.., and for each item, it creates a <ul>

Answer №2

Here is a simple solution: swap out your <script> tag with the following code:

<ul>
    <li ng-repeat="item in items">{{ item.name }}
        <ul id="items">
            <li ng-repeat="list_item in item.list">{{ list_item }}</li>
        </ul>
    </li>
</ul>

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

Showing a JSON array response on a TextView without including the array name

Is it possible to transfer JSONArray without specifying a JSON name? [{ "points": 411, "type": "C" }, { "points": 1600, "type": "G" }, { "points": 13540, "type": "I" }] The points need to be displayed on 3 separate TextViews, not ...

Improving the efficiency of calculating sliding window averages

I have a set of stock data that requires manipulation through various calculations. I have utilized numpy arrays for this purpose, which are considerably faster than Python's built-in functions. However, the execution time of my code is longer than an ...

The challenge with encoding URL in Ajax requests

I am trying to send an encrypted message along with the corresponding key (two-way encryption) to a PHP page for decryption, and then receive the decrypted result in the response. Below is an example of how I am attempting to send the encrypted message us ...

Re-activate video playback after 30 seconds of user inactivity (using RxJs)

My intention is to provide a brief explanation of the functionality I am looking for. Essentially, when a video is playing, I want it to pause if a user clicks on it, allowing them to do something else. Then, after 30 seconds of idle time, I need the video ...

Instructions on creating a vertical height adjustment handle for a website

Is there a way to create a 100% height div that can be divided by a draggable border vertically? Take a look at my fiddle to see what I have so far: http://jsfiddle.net/k5rtbzs5/ This is the HTML code: <div class="column"> <div class="top"> ...

Chrome displaying an extJs Button image

Could it be that Chrome is evolving into the new IE in terms of CSS issues? Here is the code I have for creating ExtJS buttons within an accordion: var button = Ext.create('Ext.Button', { text: '<img src="'+resp.sellers.externa ...

Creating a straightforward Theme Changer feature using Vue.js

Check out this tutorial for creating a simple Dark/Light theme switcher using Tailwind CSS. This tutorial utilizes vanilla JS and only requires a single app.js file. If I want to incorporate this into a Vue project, should I simply paste the code into ~/s ...

How to load a text file into a C++ array

I am attempting to input 20 names from a text file into an array of strings and then display each name on the screen. string creatures[20]; ifstream dataFromFile; dataFromFile.open("names.txt"); for (int i=0; i < creatures->size(); i++){ dataFro ...

Is there a way to position the angular loading bar inside a specific 'div' instead of at the top of the page?

Recently, I integrated angular-loading-bar.js into my project to visually represent the progress of http calls. By default, the blue progress bar appears at the top of the screen. However, I wanted to customize it so that it would appear within a specific ...

When you attempt to "add website to homescreen" on an iPhone, Ajax malfunctions

I have a unique website feature that utilizes ajax to dynamically load content when the user interacts with certain buttons. Everything functions smoothly up until a user tries to access the website through the "add to homescreen" option on mobile Safari a ...

Creating a custom theme for a tree panel in Ext JS 4

I'm looking to start customizing a Sencha 4 Tree panel, adjusting elements like text size and background colors. So far, I haven't been able to figure out the right approach, whether it's through viewConfig or some other method. Here's ...

Exploring Latitude, Longitude, and SVGs

In my attempt to visually represent an airport and its airspace using an SVG, I have encountered a persistent issue with the y-axis and its conversion. Despite verifying the coordinates multiple times, the positioning of the lines representing the runways ...

Tips for accessing form data that has been automatically uploaded in PHP

I've been trying to automatically post data using JavaScript and retrieve it in a PHP file. However, I am facing an issue where the PHP file is not able to retrieve the data. I have set up an automatic form that takes input from another form and send ...

Struggling to get getInitialProps working in dynamic routes with Next.js?

I am encountering an issue. The return value from the getInitialProps function is not being passed to the parent component. However, when I console.log the values inside the getInitialProps function, they appear to be correct. Here is the code snippet: i ...

Contrasting the Javascript onload event with plain script within an html page

Can you identify the distinction between these two code snippets: Sample 1: <script type="text/javascript> function myfunc () { alert('hi'); } window.onload = myfunc; </script> Sample 2: & ...

Tips for refreshing a page in Vue.js

I am facing an issue with updating a table on my page after deleting a row. Each row in the table has a delete button and I have tried using window.location.reload() but it didn't work. </va-card> <br/> <va-card > ...

Trigger an endless loop upon window.onload event

Every now and then, when a user opens the page, it starts flickering and resizing itself. After checking the log, it appears that the submit function is being called multiple times, but I can't reproduce this issue in my own environment. Is there som ...

Tips for locating a value that differs from an item in a v-autocomplete box

I am using a v-autocomplete component: <v-autocomplete v-model="fromPrice" :items="listOfFromItems" dense solo label="from" hide-detail ...

Is it possible to create a personalized serialize form when sending an AJAX POST request

How can I format form data on an AJAX POST request differently than the default $("#formid").serialze()? The current result is not suitable for my needs, as it looks like this: `poststring="csrfmiddlewaretoken=bb9SOkN756QSgTbdJYDTvIz7KYtAdZ4A&colname= ...

Using an intermediate variable is required when assigning arrays in C++

Strange issue I am facing where array assignment only works with an intermediate variable. Let me explain the scenario: struct A { int values[4]; }; std::vector<A> items; The items vector resides in a class defined in its header file. The vect ...