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

Could there be a scenario where the body onload function runs but there is still some unexec

I am feeling confused by a relatively straightforward question. When it comes to the <body> tag being positioned before content, I am wondering about when the body onload function actually runs - is it at the opening tag or the closing tag? Additio ...

Producing asynchronous JavaScript events using a browser extension (NPAPI)

Currently in the process of developing a web browser plugin using NPAPI. The issue I am facing is that my plugin requires a worker thread to handle certain tasks, and I need to pass events back to JavaScript as the worker progresses. However, due to the N ...

What is the best way to transfer the search query to a table filter when working with multiple JavaScript files?

I am struggling with passing the search query from my search file to my table file. The data for my datagrid table is retrieved from a database using an API call, and the table code is in one file while the search functionality code is in another file. I h ...

Generate random images and text using a script that pulls content from an array

My goal is to have my website refresh with a random piece of text and image from an array when a button is clicked. I have successfully implemented the text generation part, but I am unsure how to incorporate images. Here is the current script for the text ...

Leveraging Javascript to generate universal HTML content for various Javascript files

Present Situation: I have a timesheet feature that enables users to input their leave, TOIL, and sick days along with the respective hours. Additionally, there is a table that dynamically adds a new row every time the plus button is clicked using the foll ...

Adjust the button's hue upon clicking it

The current function is operational. Upon pressing the button, it toggles between displaying "click me" and "click me again". However, I desire the button to appear blue when showing "click me" and red when displaying "click me again". <!DOCTYPE html ...

What is the best location to place AngularJS scope $watch functions?

I am currently facing an issue where I need changes in an AngularJS scope to trigger actions in a model. To achieve this, I utilize the $scope.$watch() method in my item controller and integrate those controllers into directives. The issue arises when an i ...

The error message "Cannot call expressjs listen on socket.ip" indicates that there

Currently working on a project involving websockets, but encountering an error in the code below: TypeError: require(...).listen is not a function Here's what I have tried so far: const app = require("express")(); const port = 3800; const ...

What is the best way to retrieve the data from this date object?

How can I access the date and time in the code below? I've attempted using functions within the Text block without success. It's unclear to me what mistake I'm making or how to correctly access this object, or transform it into an object th ...

Tips for managing @ManyToMany relationships in TypeORM

In this scenario, there are two distinct entities known as Article and Classification, linked together by a relationship of @ManyToMany. The main inquiry here is: How can one persist this relationship effectively? The provided code snippets showcase the ...

Mastering card sliding and spacing in React NativeLearn how to effortlessly slide cards horizontally in your React

My aim with the following code snippet is to achieve two objectives: Apply a margin of 20 units to each card Display all four cards in a single row, allowing users to swipe horizontally Unfortunately, I have not been successful in achieving either of th ...

Having trouble deploying a Heroku app using Hyper? Here's a step-by-step guide to

After running the following commands: https://i.stack.imgur.com/WZN35.png I encountered the following errors: error: src refspec main does not match any error: failed to push some refs to 'https://git.heroku.com/young-brook-98064.git' Can anyon ...

Combining Angular Scripts with Model-View-Controller

For my shell page "index.html," I am required to include all the necessary files such as js, css, etc. Example : <!-- Third party libraries --> <script type="text/javascript" src="scripts/angular.min.js"></script> <script type="text/ ...

What is the method to create a resizable table column border rather than resizing the bottom corner border?

At the moment, we are able to resize the table border when we drag the corner. However, my goal is to enable resizing on the right side of the full border. Below is the CSS code for resizing: th{ resize: horizontal; overflow: auto; min-width: 100px! ...

Using the React UseEffect Hook allows for value updates to occur within the hook itself, but not within the main

I am currently utilizing a font-picker-react package to display fonts using the Google Font API. Whenever a new font is chosen from the dropdown, my goal is to update a field value accordingly. While the 'value' updates correctly within the ...

What is the best way to initiate an onload event from a script embedded within a jquery plugin?

Currently, I am in the process of developing a jQuery plugin. One issue that I have encountered involves a script tag being dynamically added for LivePerson.com. The script is supposed to trigger an onLoad function specified in the configuration. However, ...

The importance of dependencies in functions and testing with Jasmine

In troubleshooting my AngularJS Service and Jasmine test, I encountered an issue. I am using service dependency within another service, and when attempting to perform a Unit Test, an error is thrown: TypeError: undefined is not an object (evaluating sso ...

Discover the way to utilize the java enum toString() function in jQuery

In my Java Enum class called NciTaskType, I have defined two tasks: Pnd Review Woli and Osp Planning. public enum NciTaskType { PndReviewWoli, // 0 OspPlanning, // 1 ; @Override public String toString() { switch (this) ...

Button ng-click with identical function parameters

I am facing an issue with two buttons that have the same ng-click but different parameters. <label class="item item-input"> <button ng-click="takePicture(true)">Save Settings</button> <button ng-click="takePicture(false)">Choos ...

What was the reason for the removal of the `encoding` keyword argument from json.loads() function in Python 3.9?

The json package's official documentation explains: json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)¶ As of version 3.6: The s parameter now supports bytes or bytear ...