Utilizing the power of Angular's $resource within a factory to showcase information stored in a deeply nested

Just starting to explore the world of $resource concepts and facing a challenge with a piece of code that involves fetching data from a nested JSON. I've created a factory method that successfully retrieves the data and I can see it in the response header of the console. However, I'm struggling to actually print it out.

var f = angular.module("FactModule", ['ngResource']);

f.factory("MenuFactory", function($resource){
    var menuitems =[];
    var menuResource =[];
    var menuResource = $resource("http://localhost:3000/items/:id", {"id":"@mid"},{myupdate:{method: "PUT"}})
    return {
        getMenuItems: function(){                  
         menuitems = menuResource.get();

            console.log(menuitems); 

        },


    }
})

Here is the JSON data I'm working with:

{
    "items":
            {
                "wsmenuitems": [
                {
                  "code": "AB201",
                  "name": "ABCD",
                  "price": "20.5",
                  "description": "ABCD",
                  "id": 2
                },
                {
                  "code": "901",
                  "name": "XYZ",
                  "price": "25",
                  "description": "XYZ,
                  "id": 5
                }
              ],
               "wsorderitems": [
                {
                  "code": "AB201",
                  "name": "XYA",
                  "price": "20.5",
                  "description": "XYA",
                  "id": 2
                },
                {
                  "code": "901",
                  "name": "PQR",
                  "price": "25",
                  "description": "PQR",
                  "id": 5
                }
              ]
            }
}

Below is the controller I'm using:

c.controller("MenuController", function($scope, MenuFactory){


    $scope.itemsList = MenuFactory.getMenuItems();


});

And here is the corresponding HTML code:

<tr ng-repeat="menuitem in itemsList">
                    <td>{{$index}}.{{menuitem.name}}</td>
                    <td>{{menuitem.price}}</td>
                    <td><button class="btn btn-primary" ng-click="placeOrder(menuitem)" ng-disabled="itemAdded($index)">Order <i class="glyphicon glyphicon-shopping-cart"></i></button></td>
                </tr>

Answer №1

Your factory code is missing a return statement. You can check out this example on jsfiddle: example.

var f = angular.module("FactModule", ['ngResource']);

f.factory("MenuFactory", function ($resource) {
    var menuitems = [];
    var menuResource = [];
    var menuResource = $resource("http://localhost:3000/items/:id", {
        "id": "@mid"
    }, {
        myupdate: {
            method: "PUT"
        }
    })
    return {
        getMenuItems: function () {
            return menuResource.get().$promise;
        },
    }
})

Here is the controller code:

MenuFactory.getMenuItems().then((data) => {
    $scope.itemsList = data;
}).catch((err) => {
    console.log(err);
})

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

Display the chosen HTML template in real-time

Recently, I started using Angular 2 and encountered an issue that I need help with. 1] I have created 2-3 templates for emails and SMS that will display predefined data. 2] I have also designed a screen with a dropdown menu containing options like email ...

What is causing the issue in retrieving the JSON response from Django using the JavaScript Fetch API?

I am inexperienced with JavaScript. Currently, I am working on a project that involves using Django in the backend. In this project, my Django views function will generate a JSON response that my JavaScript fetch will retrieve. Below is the Django views fu ...

Tips for retrieving HTML file content as a string using JavaScript

I'm looking to retrieve the contents of an HTML file using JavaScript and store it as a string. I tried writing some code for this purpose, but unfortunately, I encountered an error: Error: Cannot find module 'xmlhttprequest' Could someone ...

Using MongoDB in a feathers.js Hook

I'm struggling to make a feathers.js hook wait for a MongoDB call to complete before proceeding. I've tried using returns and promises, but so far nothing has worked. How can I ensure the hook waits for the database query to finish? ...

The color used to highlight questions on Stackoverflow

Could someone please help me identify the specific color that stackoverflow uses to highlight the background when a question answer link is followed? For instance, take a look at this link: Is there a float input type in HTML(5)? Appreciate any assistanc ...

Issue with Jquery .on() causing toggleClass function to not trigger

Adding a column dynamically to a table on click with JS/Jquery is achieved as demonstrated below $("#btn").click(function(){ $('#week_title').append('<th>Week '+count+'</th>'); count++; $('.tag&ap ...

Tips for refreshing the current page with passing a parameter in the URL?

To achieve the functionality of reloading the page whenever different buttons are pressed and sending a String to the same page, I need to take that String on created() and use it to send an HTTP Get into my Database. My current setup looks like this: exp ...

Is it Possible to Customize the Appearance of a Broken Link Using CSS?

Can you change the color of broken links on your site to distinguish them from working ones? For example, making working links blue and broken links red. If CSS is not an option, is it possible to use JavaScript to detect broken links and style them diffe ...

managing the AJAX server's response

Struggling with a seemingly simple project where a button click should display a random saying generated from PHP, I don't have access to the PHP code and feel a bit lost. The issue seems to be in how I'm handling the server response (the handleS ...

Utilizing Angular Components Across Various Layers: A Guide

Consider the following component structure: app1 -- app1.component.html -- app1.component.ts parent1 parent2 app2 -- app2.component.html -- app2.component.ts Is it possible to efficiently reuse the app2 component within the ap ...

``Protect your PDF Document by Embedding it with the Option to Disable Printing, Saving, and

Currently, I am facing a challenge to enable users to view a PDF on a webpage without allowing them to download or print the document. Despite attempting different solutions like Iframe, embed, PDF security settings, and Adobe JavaScript, I have not been s ...

Is it possible to capture and store server responses on the client side using Node.js and React Native?

Here's a POST request I have: router.post("/projects", async (req, res) => { const { projectName, projectDescription, projectBudget, projectDuration, industry, companyName, numberOfEmployees, diamond, } = req.bod ...

Encountering an "ActionView::MissingTemplate" error when trying to render a basic JSON head response

In one of my controller files, I am using the following code snippet: respond_to do |format| format.html{ redirect_to :me, :flash => {:error => t('quest_histories.misc.bad_request')}} and return format.json{ head :method_not_allowed } ...

Function in PLSQL iterates through intricate JSON structure

For those dealing with a complex JSON type, the question of how to loop through such intricate data arises. Is there an Oracle function that can effectively traverse this complex type? If so, how can it be implemented? [[{"PONumber":1,"ItemN ...

Utilizing AngularJS, combining ng-repeat and filter functions that can be triggered directly from the controller

I have a burning question to ask. Here's the HTML code snippet: ng-repeat="item in obj.Items | filter:someFilter" And here's the JS code snippet: $scope.someFilter = function (item) { ... } It all works perfectly fine. However, I am faced wi ...

Server experiencing slow performance with Node.js formidable file uploads

When sending files as form data along with some fields using an http post request in angular.js and receiving file in app.post in node.js, the performance is inconsistent. While local testing shows a fast upload speed of 500 mb/sec with formidable, on the ...

Guide to successfully formatting and outputting JSON on a Jersey RESTful web service

After incorporating a Jersey library and a media JSON library into my application, the XML configuration looks like this: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3. ...

The sequence of synchronous execution within a Promise

I encountered a problem while attempting to test a Promise within an event listener. Although everything seems to be working fine, the execution order is not as expected. var test = document.querySelector('#test'); test.addEventListener(' ...

Employing the Confirm() function within the onbeforeunload() event

Is there a way to prompt the user with a confirmation box before exiting a page using JavaScript? If the user clicks "OK", a function should be executed before leaving the page, and if they click "Cancel", the page should remain open. window.onbeforeunloa ...

To ascertain whether the mouse is still lingering over the menu

I have a condensed menu construction that unfortunately cannot be changed in HTML, only CSS and JS modifications are possible! $('span').on("hover", handleHover('span')); function handleHover(e) { $(e).on({ mouse ...