Increase the iteration in a nested ng-repeat using a function in AngularJS

I have a nested ng-repeat and I am trying to retrieve the overall count of all records.

Despite my attempts to declare a variable within the view and increment it, it doesn't seem to work as expected.

Here is the current code snippet:

<body ng-app="app">
  <div class="table-responsive" ng-controller="quotesController">
    <div ng-repeat="info in datos2 track by $index">
      <h2><strong>{{info.name}}</strong></h2>
      <div ng-init='count()' ng-repeat="dato in data track by $index">
        <span>{{dato.name}}</span>
        <br> Position {{id}}
        <br />
      </div>
    </div>
  </div>
</body>

AngularJS Code:

$scope.count=function(){
    number = number + 1; 
    $scope.id=number;  
}

My goal is for each ng-repeat loop to display the corresponding position number.

Example:

Name 1 ITEM 1 - Position 1

ITEM 2 - Position 2

Name 2 ITEM 1 Position 3

ITEM 2 - Position 4

Name 3 ITEM 1 - Position 5

ITEM 2 - Position 6

http://plnkr.co/edit/I5IWOXGmzbu0UNqn04ha?p=preview

Answer №1

To implement a global counter in AngularJS, you can create a controller that returns the counter value and assign it to a scope variable using ngInit within nested ngRepeat. Here is an example:

// AngularJS controller
angular.module('app', [])
.controller('counterController',
  function counterController($scope) {
    $scope.items = [
      { "name": "Item 1" },
      { "name": "Item 2" },
      { "name": "Item 3" }
    ];
    
    var count = 1;
    $scope.getCount = function() {
        return count++; 
    };
});
<body ng-app="app">
  <div class="container" ng-controller="counterController">

    <div ng-repeat="item in items track by $index">
      <h2><strong>{{item.name}}</strong></h2>
      
      <div ng-init='counter = getCount()' ng-repeat="subItem in items track by $index">
        <span>{{subItem.name}}</span>
        <br> Counter: {{counter}}
        <br />
        <br>
      </div>
      
    </div>
  </div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

Answer №2

You might want to consider using ngInit in this scenario.

<body ng-app="app">
  <div class="table-responsive" ng-controller="quotesController" ng-init="totalCount = 1">
    <div ng-repeat="info in datos2 track by $index">
      <h2><strong>{{info.name}}</strong></h2>
      <div ng-repeat="dato in data track by $index" ng-init="position = totalCount++">
        <span>{{dato.name}}</span>
        <br> Position {{position}}
        <br />
      </div>
    </div>
  </div>
</body>

Answer №3

To calculate the value, you can utilize the code:

{{($parent.$index*data.length)+($index+1)}}

<div ng-repeat="info in datos2 track by $index">
  <h2><strong>{{info.name}}</strong></h2>
  <div ng-init='count()' ng-repeat="dato in data track by $index">
     <span>{{dato.name}}</span>
     <br> Position {{($parent.$index*data.length)+($index+1)}}
     <br />
     <br>
  </div>
</div>

Visit this link for more details.

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 is the best way to import all Vue3 components asynchronously?

I've been struggling to get the components to work properly. My goal is to store component names in an array, import them asynchronously, and then somehow assign them to app.component. I've spent about six hours on this and just can't seem t ...

Exploring the depths of design in material-ui

I've just started diving into material-ui and decided to create a simple app in the SandBox: https://codesandbox.io/s/eager-ride-cmkrc The styling using jss is a bit unusual for me, but with your help on these two exercises, I'm sure I'll ...

Converting a PHP array to a JavaScript array causes an issue of undefined variable when attempting to access a PHP array that has

I've been searching through other questions without finding the answer, so I'm reaching out for help with my specific issue. My problem is transferring a php array to a javascript array. In my code editor (phpStorm), I'm getting an error st ...

leveraging an AngularJS service within the view

My goal is to share data between a view and a controller, so I decided to create a service. However, when I tried to use the service in the view to set the data, it didn't work as expected. Upon further investigation, I believe the issue lies within t ...

Is it possible for me to recover the original password from a hashed password?

I am currently working on a hybrid mobile application that uses Node.js as the backend to store data in MongoDB. The server is set up correctly and I have defined routes to handle user requests. For password security, I am utilizing bcrypt to store hashed ...

Drag and Drop functionality enhanced with jQuery

Are there any unique drag and drop plugins that resemble the functionality on this website: , but also have the ability to save block positions in cookies after dragging? ...

Ways to eliminate special characters in HTML

When I retrieve a URL from Python and attempt to add it as a hyperlink in a table, the resulting link does not display correctly. Here is the code snippet: <tr ng-repeat="a in results" class="text-center"> <td style="font-size:12px" layout="r ...

Guide to sorting data by the status value within a JavaScript object?

I have a JavaScript object structured like this: { "3": { "id": 3, "first": "Lisa", "last": "Morgan", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbd7d6d4c9dcdad5fbdcd6dad2d795d8d4d6">[email&# ...

What is the proper way to set up state with localStorage in Nuxt.js when using Universal Rendering?

Unique Situation In my unique setup, I have a specific flow that involves storing a token in localStorage, even though I know it's not the recommended practice. Every time my Nuxt App is launched, I need to retrieve the token from localStorage, valid ...

Validating inputs with pristine Vue.js

I am working on creating a vue.js based form validation system that validates input on-the-fly without the need for page refresh. Currently, I have implemented the following code for email field validation: <div class="container" id="forms" > <l ...

Printing in Firefox is ineffective, but functions smoothly in alternative browsers

I'm currently working on customizing some content specifically for printing, so I've implemented a hook import { useState } from 'react' const usePrint = () => { const [isPrinting, setIsPrinting] = useState(false) const hand ...

Creating interactive navigation bar effects with scroll and click functionality using jQuery

Is there a way to make the navigation highlight when a user clicks on it and also scrolls to the corresponding section? Currently, I am facing an issue where only the third navigation event highlights, most likely because when navigating to the fourth or f ...

I am looking to dynamically insert a text field into an HTML form using jQuery or JavaScript when a specific button is clicked

This is my code snippet: <div class="rButtons"> <input type="radio" name="numbers" value="10" />10 <input type="radio" name="numbers" value="20" />20 <input type="radio" name="numbers" value="other" />other </div> ...

Can a drag-and-drop feature be created for a hexagonal shape?

The hexagonal grid How can I implement a drag and drop feature for circular elements that will snap to the hexagonal grid shown above? Additionally, I would like to log the starting and arriving coordinates of each element. My initial idea was to track cl ...

Utilizing a for loop in jQuery or JavaScript to dynamically generate buttons

I'm struggling with dynamically creating buttons through a loop. I am new to this, so I'm not sure where I'm making a mistake. Here is what I have so far. Any suggestions? <html lang="en"> <head> <meta charset="UTF-8"> < ...

Unable to retrieve Angular Service variable from Controller

I am facing an issue with my Angular Service. I have set up two controllers and one service. The first controller fetches data through an AJAX call and stores it in the service. Then, the second controller tries to access this data from the service. While ...

Enhancing date formatting with Angular and Pikaday

I am currently utilizing the angular-pikaday plugin (available at https://github.com/nverba/angular-pikaday) and encountering an issue with date formatting. My objective is to have a model containing a date string formatted as YYYY-MM-dd. To address this ...

Ways to retrieve a file from a specific location using fetch/axios?

For my research, I need to utilize certain network APIs such as fetch or axios to access a local file without using the fs module or importing them directly. I attempted to use both fetch and axios but found that they do not support fetching local files, ...

Is it possible for HTML, AJAX, and PHP to work together seamlessly in synchronous harmony? Or could

After extensive research, I have managed to find a more efficient way to connect JavaScript to PHP using Ajax. My main goal was to reduce the amount of code while maintaining maximum speed. One breakthrough I made was passing AJAX a value by Object, allowi ...

Is it possible to retrieve the class of a related element without using jQuery?

To retrieve the value of 'I Love' from the class track-songs within the cousin element of 'p', I am looking to start from the point where 'show lyrics' (using arrow) is clicked, which is triggered by the 'a' element. ...