Utilizing ng-repeat to iterate over a nested array

I need help figuring out how to properly loop through a JSON array and its ingredients/directions array using ng-repeat. The current method I have attempted is not working as expected. Any suggestions or advice would be greatly appreciated! Thank you.

Controller:

recipeControllers.controller('DetailsController', ['$scope', '$http','$routeParams',
function($scope, $http, $routeParams) {
$http.get('app/data.json').success(function(data) {
    $scope.recipe = data;
    $scope.whichItem = $routeParams.itemId;
    $scope.recipeIngredients = recipe[whichItem].ingredients;
}]);

HTML:

<div class="recipe">
    <div class="ingredients">
        <ul>
            <li ng-repeat="item in recipeIngredients">{{recipeIngredients[whichItem].ingredients}}</li>
        </ul>
     </div> 
</div>

JSON Data:

    [
  {
    "dish":"thai_chicken_satay",
    "ingredients": ["chicken", "sauce", "stuff"],
    "directions": ["step1", "step2", "step3"]
  },

  {
    "dish":"duck_confit",
    "ingredients": ["duck", "confit", "otherstuff"],
    "directions": ["step1", "step2", "step3"]
  }

]

Answer №1

When you properly assign $scope.recipeIngredients (meaning that whichItem is correctly set and corresponds to an actual object in your JSON data), then $scope.recipeIngredients will already be pointing to an array of ingredients (for example, ["duck", "confit", "otherstuff"]). To iterate over these items, all you need to do is:

<li ng-repeat="item in recipeIngredients">{{item}}</li>

If you want to iterate over the entire data array of recipes, you will need a nested ng-repeat as shown below:

<div ng-repeat="recipe in recipes">
  <div>{{recipe.dish}}</div>
  <ul>
    <li ng-repeat="item in recipe.ingredients">{{item}}</li>
  </ul>
</div>

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

Experiencing difficulties when conducting a Karma test on an Angular service

My examination is: 'use strict'; (function() { describe('Service: Assessment', function () { var $httpBackend; // load the service's module beforeEach(module('mean')); var AssessService; beforeEac ...

How to utilize a Jquery loop, implement a condition, and store the results in

After using dd() in PHP, the array displayed is as follows: 1 [▼0 => "1,18,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,19,20,21,22,23,24"] I need to iterate through the array and o ...

Split total based on checkboxes toggled with JavaScript

I'm facing a challenge. I have a total sum of donations collected, for example, 10€. Additionally, there are various NGOs that one can select to donate to. Individuals have the option to toggle on/off which NGO's they wish to contribute toward ...

Experimenting with an rxjs service to perform a GET request within the component

When calling the service function, the syntax is as follows: get getLayerToEdit(): BehaviorSubject<VectorLayer> { return this.layerToEdit; } This function is then invoked in the ngOnInit method like this: ngOnInit() { this.annoServic ...

"Troubleshooting: Why is my Bootstrap modal window only printing a

I've encountered an issue with printing the content of a Bootstrap modal window. Previously, the code I had was working fine but now it seems to be malfunctioning. Content is dynamically added to the form using appendChild() in a separate function. Ho ...

Struggling with extracting an array of objects from a JSON file and accessing individual attributes within each object?

As a newcomer to Typescript, I am eager to work with JSON and access its objects and attributes. However, I am encountering difficulties in achieving this. I have attempted using functions like 'for of' and 'for in', but unfortunately, ...

Invoke the prototype function through an onclick event after dynamically adding a button

Within my code, I have created two prototype functions named showPopup and buildView. The buildView function is responsible for generating dynamic HTML that includes a button. My intention is to invoke the showPopup function when this button is clicked. Ho ...

Issue with styled-components not being exported

Issue: ./src/card.js There was an import error: 'Bottom' is not exported from './styles/cards.style'. card.js import React from 'react' import { Bottom, Color, Text, Image } from "./styles/cards.style"; fu ...

The Growth of Integer Array

Curious about how to dynamically expand an integer array in C? I recently learned about malloc, realloc, and sizeof but could use a bit more guidance on how they function. Could someone provide a simple example of how to achieve this in C? ...

Transmitting the Flag between PHP and JavaScript

I need help with setting a flag in PHP and accessing it in JavaScript. Currently, I have the following code: PHP if ($totalResults > MAX_RESULT_ALL_PAGES) { $queryUrl = AMAZON_SEARCH_URL . $searchMonthUrlParam . ...

Struggling to showcase array data in a visually appealing table format?

Hello, I am currently facing the following issue Here is a snapshot of my current website; https://i.sstatic.net/pNXNx.png I am trying to display content in a table from an array stored in a JSON file. Initially, I used a foreach loop which worked perfe ...

Should Angular JS pages be requested from the server or not?

I recently delved into learning AngularJS. After inserting Angular code into my HTML page, I attempted to view it in the browser but encountered issues with Angular JS not functioning. However, when I accessed the page through the server, it worked perfe ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

Discovering the closest major urban area using geonames

One of my PHP functions retrieves the closest nearby city based on a given latitude and longitude: function findCity($lat, $lng, $username) { $json_url = "http://api.geonames.org/findNearbyPlaceNameJSON?lat=" . $lat . "&lng=" . $lng . "&us ...

What is the best way to retrieve the page slug within the layout file in Next.js, specifically when using the app folder structure?

In my latest project, I have implemented a nested layout using the new app folder. Within this layout, I have included a header that appears across all pages in the path www.mysite.com/some-slug. One issue I am facing is with the signup button located in t ...

What are the implications of declaring a controller as a variable within itself or utilizing $scope?

As I dive into learning and utilizing AngularJS, certain concepts still remain unclear to me. Here is my query: within my application, there is a controller that utilizes $http to fetch data from the backend upon initialization. Following a comprehensive ...

Customize the text that appears when there are no options available in an Autocomplete component using React

Recently, I came across this Autocomplete example from MaterialUI that caught my attention. https://codesandbox.io/s/81qc1 One thing that got me thinking was how to show a "No options found" message when there are no search results. ...

Exploring the versatility of NodeJS in conjunction with node-rest-client functions for sending dynamic data to HTML front end

As someone who is fairly new to NodeJS, I am eager to ask my question in a clear manner. My objective is to develop a NodeJS application that utilizes the node-rest-client to retrieve data and then display it asynchronously in HTML on the client side. I h ...

Can you explain NodeSource in simple terms, and what purpose does it serve?

Not too long ago, I delved into researching how to effectively host a MEAN stack web application on AWS. During my quest for knowledge, I stumbled upon a tutorial that caught my eye. The one I ended up following can be found at https://www.youtube.com/wat ...

Google Feed API - Retrieving saved data from RSS feed cache

We have implemented the Google Feed API to display our latest blog posts on our website. However, even after 24 hours, our most recent post is still not appearing on our site. Despite confirming that the RSS feed contains the newest content, it seems that ...