Nesting ng-repeat within another ng-repeat for dynamic content generation

I am currently working on a page that requires displaying boxes (using ng-repeat) containing information about channels and their corresponding cities.

The issue I am encountering arises when repeating the second ng-repeat:

<table class="table table-condensed" ng-init="nitsCh = [objsCh[$index].nit]">

This code should extract the $index of the first ng-repeat and generate a new array with the cities where the channels will be displayed. It accomplishes this task perfectly. However, applying the second ng-repeat using this array does not yield the expected outcome.

My HTML structure is as follows (Note: I need to utilize the index value instead of objCh.name since these boxes are positioned within columns)

<div class="box box-solid box-default" ng-repeat="(indexO, objCh) in objsCh track by indexO" ng-if="indexO%4==0  && indexO<=10">
  <div class="box-header"> 
    <div class="pull-left"> 
      <img src="dist/img/channels/{{ objsCh[indexO].pic }}" data-toggle="tooltip" title="" data-original-title="Change channel logo"> 
      <h3 class="box-title">{{ objsCh[(indexO)].name }}</h3> 
    </div> 
    <div class="box-tools pull-right"> 
      <button class="btn btn-box-tool" data-toggle="tooltip" title="" data-original-title="Add or Remove NIT"><i class="fa fa-plus"></i></button> 
    </div> 
  </div> 
  <div class="box-body"> 
    <table class="table table-condensed" ng-init="nitsCh = [objsCh[indexO].nit]"> 
      <tbody> 
        <tr> 
          <th style="width: 10px">#</th> 
          <th>Nit</th> 
        </tr> 
        <tr ng-repeat="(indexN,nitCh) in nitsCh track by indexN"> 
          <td>{{ objsCh[(indexO + 1)].nit[indexN].num }}</td>
          <td>{{ objsCh[(indexO + 1)].nit[indexN].name }}</td>
        </tr> 
      </tbody>
    </table> 
  </div> 
</div>

The JavaScript file appears like this:

var app = angular.module('appApp', []);
app.controller('ctrlApp', function($scope, $http) {

    var url = "includes/exibChNit.php";

    $http.get(url).success(function(response) {
        all = response;
        $scope.objsCh = all.channels;
    });
});

And the JSON file (generated by PHP) has the following structure:

{
    "channels": [{
        "id": "1",
        "sid": "1",
        "name": "Channel",
        "pic": "channel.jpg",
        "crc32": "A1g423423B2",
        "special": "0",
        "url": "",
        "key": "",
        "type": "",
        "city": [{
            "num": "1",
            "name": "So Paulo"
        }, {
            "num": "2",
            "name": "Rio de Janeiro"
        }]
    }, {
        "id": "2",
        "sid": "2",
        "name": "CHannel 1",
        "pic": "channel.jpg",
        "crc32": "A1F5534234B2",
        "special": "0",
        "url": "",
        "key": "",
        "type": "",
        "city": [{
            "num": "1",
            "name": "So Paulo"
        }, {
            "num": "2",
            "name": "Rio de Janeiro"
        }]
    }]
}

When testing this alternative approach, it proves effective:

<table class="table table-condensed" ng-init="nitsCh = [objsCh[($parent.$index + 1)].nit]">

However, this method cannot be employed due to the dynamic nature of the JSON nodes.

Thank you for your assistance!

Answer №1

ng-repeat generates its own $scope.

Therefore, for the nested ng-repeats, you can utilize $parent.$index, where $parent refers to the parent scope of the current repeat block.

For example:

<ul ng-repeat="section in sections">
  <li>
      {{section.name}}
  </li>
  <ul>
    <li ng-click="loadFromMenu($parent.$index)" ng-repeat="tutorial in section.tutorials">
          {{tutorial.name}}
    </li>
  </ul>
</ul>

Plunkr http://plnkr.co/edit/hOfAldNevxKzZQlxFfBn?p=preview

(adapted from this solution passing 2 $index values within nested ng-repeat)

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

Protractor's count() function fails to execute properly when called outside of a promise loop

var alerts = element.all(by.xpath("//div[@class='notification-content']")); alerts.count().then(function (val) { console.log(val); }); let compareValue = val; Is there a way to access the 'value' outside of the promise l ...

Issues arise in Angular 4 when the "Subscribe" function is repeatedly invoked within a for/switch loop

My array of strings always changes, for example: ["consumables", "spells", "spells", "consumables", "spells", "consumables", "spells", "characters", "characters", "consumables"] I iterate through this array and based on the index, I execute different .su ...

Terminal throws an error stating that no default engine was specified and no extension was provided

I have been working on executing a backend program in Node.js using MongoDB. I have created a form with two input fields for password and name. I am not utilizing any HBS or EJS and my VS Code terminal is displaying the following error: No default engine ...

Can you explain the distinction between String[] and [String] in TypeScript?

Can you explain the distinction between String[] and [String] in typescript? Which option would be more advantageous to use? ...

Display various JavaScript function outputs in an HTML table for convenient tracking

Thanks to a helpful user on this platform, I was able to capture data from a JavaScript function and display it in an html table. However, I now have another query. How can I execute the function multiple times during page load and record the results in ...

Having trouble with React's useEffect and React-Query's useQuery?

As a React newbie, I'm trying to implement global error handling using a context provider and a custom hook. Main Objective: Implementing a system to handle errors at the global level. The Issue: Errors reappear immediately after being removed. I s ...

Examples of Javascript closures in action with a for loop

I decided to stop my research here. Below is the question I have: After reading this post, I grasped the concept illustrated by the code snippet provided. var funcs = {}; for (var i = 0; i < 3; i++) { // creating 3 functions funcs[i] = functi ...

Best practice for filling an array using a promise

I am completely new to the world of modern JavaScript. My goal is to fill an array with data that I receive from a promise in a helperService. export class PeopleTableComponent implements OnInit { people: Array < Person > = []; constructor( ...

What is the best way to add a simple Search bar to the Material UI Data Grid component?

If we take a look at this data grid example: check it out here I'd like to incorporate a simple search bar similar to the one shown here Can someone provide guidance on how to add this feature to Data Grid MUI? ...

Accessing an object's property within a mapped array in a Next.js application is possible

Currently, I am attempting to iterate through an array of objects and extract the link property as a <li></li> element. However, I am facing an issue where nothing is being returned: import { useState, useEffect } from "react"; import ...

Encountering a problem during the installation of angular-route.d.ts

When trying to install angular-route using the command typings install angular-route --save -global, I encountered an error. Can someone help me resolve this issue? typings ERR! message Unable to find "angular-route" ("npm") in the registry. typings ERR! ...

When a variable is used, the .sort() method does not effectively organize the elements

When working with Nodejs and mongoose queries, I encountered an issue with using the .sort() method dynamically based on user input. While it works fine when hardcoded, I want to use a variable to determine the sorting order. However, when attempting to do ...

How to pass user-specific data to routeProvider in an Angular and Express application

I'm wondering how to pass req.user.username (for example) to all pages or globally once the user has signed in with passport. This question pertains to any data that I want accessible across all pages... On the server side, I have the following code ...

Instruction failed to produce HTML output

Currently facing a challenge with my code - I have a dynamically created span (via ng-repeat). <span my-size id="abc"></span> <span my-size id="def"></span> <span my-size id="ghi"></span> The goal is to extract the id ...

Text alignment issues cause animation to vanish

Utilizing particles.js, I set up a full-screen particle effect by specifying the animation to be full-screen with height: 100vh;. This worked perfectly as intended. However, when attempting to add text on top of the particle animation and center it vertica ...

The Query.formatError message indicates that there is an issue with the 'users.email' column in the where clause of the database query

I'm having some trouble with a piece of code. Here's my signup function : exports.signup = (req, res) => { // Adding User to Database console.log("Processing func -> SignUp"); User.create({ name: req.body.name, username: req.body. ...

The callback in Jquery getJSON does not execute even when a valid JSON response is received

My server is sending valid JSON objects (as verified by jsonlint.com) that have this structure: "{\"encryption\": {\"key\": \"gKV0oPJwC5CBQxmn\"}}" This is how my HTML file looks: <html> <head> <title&g ...

Using the same conditional statement on multiple pages within a Next.js application

I'm currently working on a project with Next.js and I've encountered an issue when fetching data from my server using the useSWR hook. There are certain conditions that need to be met in order to display specific content on the page, as shown in ...

Attempting to conceal a div element along with its contents using AngularJS

I am attempting to use AngularJS to hide a div and its contents. I have defined a scope variable initialized as false and passed it to the div in order to hide it. However, the div is still visible along with its content. <script type="text/javascr ...

What is the best way to concatenate two different values in React JSX using the "+" operator?

I have a situation where I need to take a value from an input, add 10% to it, and display the result. For example, if a person inputs 1000, the 10% of 1000 is 100, so the total result should be 1100. Currently, when I use the "+" operator, it concatenates ...