The Proper Method of Displaying Data from a JSON File Using AngularJS

I'm having trouble getting the data from a JSON file (click on the "Json File" link to view the structure). I'm not sure what to put after "$Scope.listOfRecipe=". I tried using response.data.recipes, but it's not working and causing errors.

angular.js:12520 TypeError: Cannot read property 'recipes' of undefined
      at recipesController.js:10
      at angular.js:10296
      at angular.js:14792
      at r.$eval (angular.js:16052)
      at r.$digest (angular.js:15870)
      at r.$apply (angular.js:16160)
      at g (angular.js:10589)
      at T (angular.js:10787)
      at XMLHttpRequest.w.onload (angular.js:10728)

Here is the Json File for reference.

This is my recipesControllers.js

var myApp = angular.module('myApp', []);

 myApp.controller('namesCtrl',function ($scope, $http) {

$scope.listOfRecipe = null;

$http.get('http://164.132.196.117/chop_dev/recipe/recipes.json')
     .success(function (response) {
         $scope.listOfRecipe = response.data.recipes;
     })

});

This is my Index.html

<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>

<body>
  <div ng-app="myApp" ng-controller="namesCtrl">
    <ul>
      <li ng-repeat="x in listOfRecipe ">
        {{ x.Recipe.id + ', ' + x.Recipe.name }}
      </li>
    </ul>
  </div>
  <script src="C:/Users/Enetfirm  Server/Desktop/AngularJs/recipesController.js"></script>
</body>

</html>

Answer №1

To determine the response, you can utilize console.log(response) and make necessary adjustments to your code.

However, it is advisable to follow the standard promise pattern:

$http.get('http://164.132.196.117/chop_dev/recipe/recipes.json')
  .then(function(resp) {
    $scope.listOfRecipe = resp.data.recipes;
  })
  .catch(function(errResp) {
    // handle errors
  })
  .finally(function() {
    // upon completion, perform actions in the view
    // such as removing a spinner gif or scrolling to top
  });

Answer №2

Have you confirmed that the file is downloading in the developer tools network tab?

Ensure it is functioning correctly, and be sure to console.log both response and response.data to confirm they are present!

Since it's a JSON file, the response itself is the JSON and not res.data.

Please review and respond with your solution.

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

Activate click events when button is being held down

I'm currently working on a directive that shifts an element to the right whenever clicked. However, I want the element to keep moving as long as the button is pressed. .directive("car", function(){ return { restrict:"A", link:func ...

Creating circular patterns with looping on a canvas

My goal is to draw circles in a loop, but when I execute my code, I am encountering an unexpected result: The intention is to simply draw 3 circles in random positions. Here is my current code: for (var i = 0; i < iloscU; i++) { ctx.strokeStyle = ...

Automatically resetting the Redux toolkit store when navigating between pages in Next.js

I am a new Next user who has been using Redux with React for a while. However, I encountered many challenges when trying to integrate Redux with Next. I have decided to move on from this solution. store.js import { configureStore } from '@reduxjs/to ...

javascript issue with onchange query

The JavaScript snippet below is included in the head section of my file. <?php echo "<script language='JavaScript'>\n"; echo "var times = new Array();\n"; echo "times[0] = 0;\n"; foreach($times as $time) { echo "times[". ...

Viewing JSON data using Tshark can be a helpful tool in analyzing

When utilizing tshark to analyze a capfile in the following manner: tshark -V -r test.cap -Y 'http>0' The output obtained is as follows: ... JavaScript Object Notation: application/json Object Member Key: "ret" Num ...

The jQuery ajax request will only display the data in the HTML once

Hey there! I am facing an issue where, when I click on my button to make an ajax request, it works perfectly and displays the data on my select item. However, on clicking the button again, the data is fetched correctly but the select item shows the data t ...

How come I am unable to reach a function within an AngularJS service following the "then" promise? (refer to code)

I'm encountering an issue with this error message: TypeError: Object [object global] does not have the method 'setApiToken' angular.module("userService", ["restangular", "angular-cache"]).factory "userService", (Restangular, $angularCacheFa ...

I'm encountering an issue with Regex.test

When working with the following JavaScript code... $.post(url, data, function (json) { var patt = new RegExp('/^\[{"dID":/'); if (patt.test(json)) { //output json results formatted } else { //error so o ...

When a model is changed from within a jQuery event, Angular 2 fails to update the view

During the development process, I encountered an issue while creating a custom search panel that displayed search results in a dropdown container. In my controller, I defined the following: export class ProductSearchComponent implements OnInit { publ ...

Finding mongoose in an array of objects nested within another object

Here is the MongoDB JSON document I am working with: { categoryId: '1', categoryName: 'Outdoors Equipments', items: [ { itemId: '1', itemName: 'Camping T ...

Convert Time: segment time devoted to the main content from the time dedicated to advertisements

Can anyone assist me with solving a math problem? Let's consider two lists or arrays: Content Array 0-50 = C1 50-100 = C2 AD Array 10-20 = A1 30-60 = A2 80-140 = A3 The desired output should be: 0-10 = C1 10-20 = A1 20-30 = C1 30-60 = A2 60-80 = C ...

Step-by-step guide on populating an array with variables in Vue.Js for creating a bar chart

I am attempting to dynamically add values from variables to an array in order to create a bar chart using Vue.js My initial attempt involved adding values like this: series[0]=ServiceArea1;. This is my current progress: barChart: { data: { s ...

Enhancing Accessibility for the jQuery Countdown Plugin

Seeking to enhance the accessibility of my website's jQuery countdown, I am striving to adhere to WAI-ARIA guidelines. The specified requirements are as follows: Ensure the area is live so it updates dynamically with the countdown display. Avoid re ...

Loop through the last modified file

I am currently working on a webpage that displays the "last-modified" date of each file it loads: Have you noticed how the dates are loaded one by one as the page makes calls to the header? If not, try hitting F5 to refresh the page. Is there a way to im ...

AngularJS is patiently anticipating the population of the scope for ng-show

I have implemented ng-show to display an error message based on an array. The code I used is ng-show="!items.length". However, since the items are populated after a request, there is a flickering effect for a brief moment before the items are loaded. Is th ...

Achieving a transparent background in WebGLRender: A guide

I've been experimenting with placing objects in front of CSS3DObjects using the THREE.NoBlending hack. However, in the latest revisions (tested on r65 and r66), I only see the black plane without the CSS3DObject. Here is a small example I created: in ...

Unable to save screenshot in the report portal while running with WebDriver.io (wdio) execution

In my webdriverio project, the directory structure is as follows: e2e/ utilities/pUtil.js report/screenshot specs wdio.config.js Within pUtil.js file, I have the following code snippet: static takeScreenshot(name, failure = false, test) { const path = ...

Attempting to transform JSON information into a JSON array within the Android Studio environment

Hey there! I'm currently working on converting some JSON data into an array. I've done it in the past, but never with objects involved. Check out the JSON data I'm working with here. Below is the code I've been using to fetch and conv ...

Utilizing d3.js to filter a dataset based on dropdown selection

I am working with a data set that contains country names as key attributes. When I select a country from a dropdown menu, I want to subset the dataset to display only values related to the selected country. However, my current code is only outputting [obje ...

Exploring Android JSON parsing: transmitting images through intents

I am currently using JSON to generate a list of items. When a user clicks on an item, it opens another screen displaying details about that specific item. However, I am facing an issue with sending images to this activity. Here is the code I have for parsi ...