The output from $index in AngularJS appears to be incorrect and inconsistent

The question was too long so I edited it. Here is the angular code snippet in question:

var mod = angular
            .module("myMod",[])
            .controller("myCont",function($scope){
              var obj = [
              {name : "Monica", others :[{age:20},{salary:20000}]},
              {name : "Rachel", others :[{age:16},{salary:28000}]},
              {name : "Pheobe", others :[{age:24},{salary:30000}]}
              ]
              $scope.obj1 = obj;
             })

Additionally, here is the relevant HTML file code:

<!DOCTYPE HTML>
<html  >
    <head> 
        <script src = "angular.js"></script>
        <script src = "angularmy.js"></script>
    </head>
    <body ng-app="myMod" ng-controller="myCont">
        <div>
            <ol>
                <li ng-repeat="item in obj1" ng-init="parentIndex=$index">{{item.name}} 
                <ol ng-repeat="items in item.others">
                    <li >{{items.age }} parentIndex - {{parentIndex}} index - {{$index}}</li>
                    <li >{{items.salary }} parentIndex - {{parentIndex}} index - {{$index}}</li>
                </ol>
                </li>
            </ol>
        </div>
    </body>
</html>

However, there seems to be an issue where the output shows duplicate indices for nested list items. Why are there four outputs instead of two? Can someone please assist in identifying what might be wrong with this code?

Answer №1

Give this a shot:

<ul ng-repeat="data in item.more track by $index">
   <li>{{data.age}} - parentIndex: {{parentIndex}}, index: {{$index}}</li>
   <li>{{data.salary}} - parentIndex: {{parentIndex}}, index: {{$index}}</li>
</ul>

Answer №2

As per this discussion, the solution to your problem can be achieved through the following code snippet:

<li ng-repeat="item in data.object">{{item.name}} 
    <ol ng-repeat="o in item.children">
        <li>{{o.age}} parentIndex - {{$parent.$index}} index - {{$index}}</li>
        <li>{{o.salary}} parentIndex - {{$parent.$index}} index - {{$index}}</li>
    </ol>
</li>

Answer №3

In order to better visualize the data being displayed, it is recommended to use more descriptive variable names when working with nested ng-repeats.

Controller:

var app = angular
.module("myApp",[])
.controller("myCtrl",function($scope){
  var people = [
    {name : "Monica", details :[{age:26,salary:20000}]},
    {name : "Rachel", details :[{age:28,salary:28000}]},
    {name : "Phoebe", details :[{age:29,salary:30000}]}
  ]
  $scope.peopleList = people;
})

Template: (here I have replaced the ol with ul to avoid confusion)

<body ng-app="myApp" ng-controller="myCtrl">
    <ul>
        <li ng-repeat="person in peopleList" >Name: {{person.name}} | Person Index: {{$index}}
            <ul ng-repeat="info in person.details">
                <li>Age: {{info.age}} | Salary: {{info.salary}} | Index: {{$index}} | Parent Index: {{$parent.$index}}</li>
            </ul>
        </li>
    </ul>
</body>

The main issue was having multiple li elements inside the second ng-repeat.

Output:

Name: Monica | Person Index: 0
Age: 26 | Salary: 20000 | Index: 0 | Parent Index: 0
Name: Rachel | Person Index: 1
Age: 28 | Salary: 28000 | Index: 0 | Parent Index: 1
Name: Phoebe | Person Index: 2
Age: 29 | Salary: 30000 | Index: 0 | Parent Index: 2

Fiddle: https://jsfiddle.net/7uva6rgt/2/

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

What are your thoughts on this method for preventing scrolling?

Is there a way to prevent scrolling of the underlying content on a webpage when a modal is displayed? I found this code snippet that achieves that. (http://jsfiddle.net/77P2e/) var $window = $(window), previousScrollTop = 0, scrollLock = false; $window.s ...

Leveraging the power of static in page object models with Cypress

After researching different examples of implementing end-to-end tests on Cypress, I noticed that many developers prefer to create a new object instead of using the static method. This raises questions about why they choose this approach over utilizing stat ...

Tips for embedding HTML components within a div element through JavaScript

Can you help me transform this code into a div element using JavaScript? <div id=parentDiv> <div id="question1"> QuestionNo 1 <button onclick="setOption(1,1)">A</button> <button onclick="setOption(1, ...

Implementing Custom Directive and Events in an Ongoing Application Process

As I design a custom directive for a third-party jQuery plugin, I encounter issues with updating data using events. My directive is set to listen for these events and use $apply to ensure proper data updates from the controller. Additionally, I aim to enab ...

Take away the attention from the span element

I have been experimenting with the following jsfiddle and attempted various methods suggested in this Stack Overflow thread, but I am struggling to remove the focus from the "feedback" span after clicking on the cancel button in jQuery confirm dialog. Her ...

Send the contents of a `<ul>` element to the server using AJAX for form submission

Can someone assist me in submitting a serialized <ul> list through an AJAX post form request? I need help with this process. Below is my current code snippet. HTML: <form id="update_fruit_form" method="post" action="/update_fruits" accept-charse ...

Invoke a router inside Node.js once a route has been triggered

I am working with ExpressJS and integrating the Auth0 API for authentication, along with ReactJS on the client side. Due to some limitations of the Auth0 API that I discussed with their team, I have implemented a workaround where I send updated user detail ...

The button click event fails to trigger after entering text into an input field

I created a basic calculator. Users can input a value in the designated field and then click on the '+' button. The cursor stays in the input field, allowing users to immediately enter a new value after clicking the '+'. The mouse poi ...

Troubleshooting Three JS Projection Challenges

I have been attempting to find the centroid of a polygon in 3D space and then convert its vertices to 2D screen coordinates. Unfortunately, the code I currently have is not producing the desired results. I would greatly appreciate any assistance with this ...

Using data from a service call to bind detailInit in nested Kendo grid

I am working with an Angular directive that retrieves data source values from a Kendo grid (referred to as gridDataDisplayed). I need to use the same data source to bind it to a nested grid in detailInit. scope.gridsource = new kendo.data.DataSource({ ...

Extract item from the collection

I am struggling with the following code: app.controller('modalController', function($scope, $http,$modalInstance, $rootScope, items){ // Retrieving information $http.post('/ajax/bundle', {'items':items}).success(functi ...

When using threejs, the color set for setClearColor is supposed to be white. However, when calling an external HTML file, it unexpectedly renders as

When I call an external HTML file in Three.js, the value for setClearColor is white but it renders as black. How can I solve this issue? Click here to view the image Here are the codes from the external file: <div id="3d-modal"></div> <sc ...

Is it possible for ExpressJs compression to compress more than just static files on an HTTP request?

I am currently using Express 4.x and I have implemented compression middleware in my app.js file like so: var compression = require('compression'); var app = express(); app.use(compression()); app.use('/', require(&apos ...

Can an ongoing asynchronous call be canceled regardless of its current status?

As I enter text into my textfield widget, a request is sent to the server with every character typed in order to retrieve matching data. However, when I type rapidly, the server gets swamped with requests causing my control to freeze. To address this issu ...

When working with AngularJS, I am trying to display an element only when the ng-if condition is true and not when it is null or undefined

I have a piece of code that is meant to display a label when the condition is false, but not when it's null or undefined. The issue I'm facing is that the label is being displayed before I even click on 'false'. <div> <md- ...

Javascript - Displaying data retrieved from an external API with JSON

Seeking advice on how to effectively attach JSON values obtained from xhr.response to HTML labels. Any suggestions are appreciated. Thank you. On a different note, does anyone have recommendations for websites that provide concise explanations of basic JS ...

Exploring the DOM: A Guide to Observing the Present State with React Testing Library

Currently, I am delving into React Testing Library, drawing from my extensive TDD experience in various programming languages. The documentation for React Testing Library mentions that if getByText fails, it will "print the state of your DOM under test" h ...

JavaScript can switch the rendering mode from quirks mode to standard mode in Internet Explorer

Is it possible to switch IE from quirks mode to standard mode using JavaScript? I am unable to edit the HTML content header, and adding a new IE=edge meta tag to the head element is not effective (it displays a message stating that the mode has been set ...

Checking for any lint errors in all JavaScript files within the project package using JSHint

Currently, I am utilizing the gulp task runner to streamline my workflow. My goal is to implement JsHint for static code analysis. However, I have encountered a setback where I can only run one file at a time. Upon npm installation, "gulp-jshint": "~1.11. ...

Bringing packages from around the world into your Node.js project

In my node.js application, I have several modules where I find myself importing the same package (e.g. moment npm). I'm curious if there is a more efficient way to handle imports by centralizing all dependencies in one place and using them as global ...