AngularJs code snippet: Iterating over each element in the arrayValue using ng-repeat directive

Here is an example of an array:

 var date = {
   '2015': [{
     'month': 'Januar',
     'day': 31
   }, {
     'month': 'Februar',
     'day': 28
   }]
 };

I am trying to use ng-repeat to iterate through the days:
Desired Output:

<div ng-repeat="date in date.2015">
  {{date.month}}
  <!-- Displays 12 month names -->
  <div ng-repeat="day in date['2015'+$index]['day']" >
    {{day}}
    <!-- displays the day count based on the month-->
    <!-- The day count should start from 0 and increment up to the specified number-->
  </div>
</div>

I hope this clarifies things.
The issue with

ng-repeat="day in date.2015+{{$index}}+'.day'"
has been fixed.

Answer №1

To start, you should create a helper function within your controller that transforms your number into an array with the same length as your day's value:

$scope.range = function(n) {
    return new Array(n);   
}

If you are working with the most recent versions of angular, make sure to explicitly set a variable in the repeat for aliasing purposes. Here is a functional fiddle using the provided code

<div ng-repeat="date in date.2015">
   {{date.month}} <!-- Shows 12 month names -->
   <div ng-repeat="day in range(date.day) track by $index">
        {{$index + 1}} <!-- displays the day 31, 30, or 28 times -->
        <!-- The day should also increment from 0 to the number -->
   </div>
</div>

Adjust the second ng-repeat to utilize the controller's function to obtain the index of the ng-repeat and remember to add 1 since it starts at 0. This Plunker demonstrates how to do this with older versions

<div ng-repeat="date in date.2015">
   {{date.month}} <!-- Shows 12 month names -->
   <div ng-repeat="day in range(date.day)">
        {{$index + 1}} <!-- displays the day 31, 30, or 28 times -->
        <!-- The day should also increment from 0 to the number -->
   </div>
</div>

Answer №2

I believe I understand what you're trying to achieve. To iterate over the days, you can use the following code:

<div ng-repeat="date in date.2015">
   {{date.month}} <!-- Displays the month name -->
   <div ng-repeat="day in getDays(date.day)">
        {{day}} <!-- displays the day multiple times based on the number -->
        <!-- The day should also increment from 0 to the specified number -->
   </div>
</div>

To make this work, simply include this function in your controller:

$scope.getDays = function(num) {
    return new Array(num);   
}

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

How can I determine the length of the returned array after a successful jQuery Ajax

I am struggling with looping through the Array returned from PHP. However, when I use jQuery .length, it returns 'undefined'. 'undefined' PHP: $items = array(); $items["country"] = "North Korea", $items["fruits"] = array( ...

Is the express.json() middleware for parsing JSON request body designed to handle synchronous calls?

According to Express.js's documentation, it is recommended to avoid using synchronous functions as much as possible. This is because in high-traffic websites, the accumulation of synchronous calls can negatively impact the performance of the applicati ...

Is there a way to show an alert indicating the location of the element that was clicked on the screen?

Here is an example I am working on: link HTML CODE: <ul> <li id="#bar"> <img src="http://theimageconference.org/wp-content/uploads/2014/01/images-50x50.png"width=50 height=50></img> <p>ELEMENT 1</p&g ...

Query an array of objects for partial matches that are not case-sensitive, and then organize the results in alphabetical order

I am seeking assistance or guidance on which topics to explore for answers. As a newcomer to React, I have a code that successfully filters a list within the items object. However, I would like to switch to using a prepared JSON file instead. When I attem ...

I am having difficulty accessing the dataset on my flashcard while working with React/Next JS

I'm currently developing a Flashcard app that focuses on English and Japanese vocabulary, including a simple matching game. My goal is to link the two cards using a dataset value in order to determine if they match or not. When I click on a flashcar ...

Retrieve specified elements from Bootstrap SelectPicker

My coffee selection script uses the Bootstrap SelectPicker plug-in to choose my favorite coffees. After submitting the form, I want to save the selected values and send them to addCoffee.php?coffee=${coffee}. How can I achieve this? HTML: < ...

Unable to call upon JavaScript code from an external file

Just starting out with Spring and JavaScript! I've put together a JSP file https://i.sstatic.net/XemJ5.png In my first.js, you'll find the following method: function firstmethod() { window.alert("Enter a New Number"); return true; } H ...

What is the process for incorporating the 'url-regex' npm package into an Angular(2/4) project?

I'm currently working on a project with Angular 4 and I've run into some issues while trying to use the url-regex package within my Component. After some troubleshooting, I discovered that this approach seems to work: import * as urlRegex from ...

Tips for utilizing the async.js library in combination with the await keyword?

Currently, I am working on integrating the async library to continuously poll an API for a transaction until it is successful. router.get('/', async function (req, res) { let apiMethod = await service.getTransactionResult(txHash).execute(); ...

Combining AngularJS with Bridgeit.js for a seamless mobile web app experience

Currently, I'm working on an AngularJS web application that requires scanning a package from a mobile device. To achieve this functionality, I am utilizing BridgeIt. Unfortunately, the code I've written in Angular doesn't seem to be functio ...

Issue with AJAX loading functionality not functioning properly in Internet Explorer

For a project, I have a portfolio that I need to create. The front page consists of a div with a loader which determines the screen size upon landing and selects the content to be pulled in using ajax. The reason for this approach is due to the simplicity ...

What is the best way to display a Bootstrap toggle?

I am facing an issue with a Bootstrap toggle in a Handlebars template. When the page initially loads, the toggle is visible, however, after re-templating the Handlebars template that contains the toggle, it disappears. Before Re-Template: Initial code : ...

Arrow function in JSX syntax within a render method

After stumbling across this code snippet in a different question, I'm left scratching my head over how it actually functions: let Parent = () => ( <ApiSubscribe> {api => <Child api={api} />} </ApiSubscribe> ) I can gr ...

Is there a way to ensure my Vue variable is declared once the page has fully loaded?

I have implemented a v-for loop in my code: <div v-for="(user, index) in users" :key="index" :presence="user.presence" class="person"> <span class="cardName h4">{{ user.name }}</span> ...

Choose an option from the drop-down menu

I am currently working on a drop-down menu that displays country codes and their respective full names. Here is an example: <script> var app = angular.module('myApp', []); app.controller('myCtrl', func ...

What is the best way to download a modified canvas with filters using the solutions from stackoverflow?

There have been numerous inquiries regarding how to apply CSS filters to an image, with some solutions that don't utilize CSS filters but still achieve the desired outcome. However, for someone new to JavaScript like myself, these answers can be confu ...

Identify file size upon upload using Javascript event and allow cancellation

Currently, I am utilizing a file uploader functionality. My preference is to refrain from verifying the file size on the server side. Instead, I am in search of a method that involves monitoring the uploaded file's size periodically through a listener ...

Show the error message from passport.js authentication in the user interface

I am currently working on a new project with Sails.js and using Passport.js for user authentication. Despite having the basic authentication set up, I am struggling to display error messages in the login view when incorrect credentials are entered. I have ...

Convert unusual characters that cannot be transmitted to the API using Node.js

Hi, my name is Juraj Čarnogurský. That unique character Č is quite important to me. I need to transmit my full name from one server to an API. But the JSON format gets messed up with my last name looking like this: "firstName":"Juraj","lastName":" ...

Creating pagination in Vue using an array of objects

I'm new to Vue and arrays and I need help paginating my json array so that only 10 items are displayed per page. Currently, all the items in the array are being shown in the <tr> body. I've tried different methods without success. Can someo ...