AngularJS factory problem

I attempted to utilize Angular JS by using a factory for my data structure...

However, it seems to be malfunctioning. I simply added some basic json data to be returned by the factory, and as a result,

the script stopped working. This is a fundamental example of angularjs that involves json

to be repeated and iterated through.

Below is the angularjs code that I wrote:

var Item = angular.module("Item", ['ngRoute']);

Item.config(function($routeProvider){
    $routeProvider
        .when("/add", {
            controller : "ItemController",
            templateUrl : "index.html"
        })
        .when("/edit", {
            controller : "ItemController",
            templateUrl : "index.html"
        });
});

Item.factory("ItemsFactory", function(){

    var items = [
        { name : "Washing Powder",
        price : "2000",
        balance : 14
        },

        { name : "Shampoo",
          price : "8500",
          balance : 03
        },

        { name : "Soap",
          price : "1850",
          balance : 27
        }
    ];

    var factory = {};

    factory.getItems() = function(){
        return items;
    };

    factory.postItems() = function(){
        // POST items
    };

    return factory;

});


Item.controller("ItemController", function($scope, ItemsFactory){
    $scope.items = ItemsFactory.getItems();

    init();

    function init()
    {
        $scope.items = ItemsFactory.getItems();
    }


    $scope.AddNewItem = function(){
        $scope.items.push({
            name : $scope.NewItem.name,
            price : $scope.NewItem.price
        });
    };
});

And here is the HTML markup:

<!DOCTYPE html>
<html >
<head>
    <title>Practicing AngularJS Framework...!</title>
    <script src="angular.js" type="text/javascript"></script>
    <script src="ngroute.js" type="text/javascript"></script>
    <script src="scripts.js" type="text/javascript"></script>
</head>
<body data-ng-app="Item">
        <div data-ng-controller="ItemController">
            <div data-ng-repeat="each in items">
                <p>Item {{ each.name }} costs {{ each.price }}.</p>
            </div>
            <div>
                <input type="text" data-ng-model="NewItem.name" />
                <input type="text" data-ng-model="NewItem.price" />
                <br />
                <input type="submit" value="Add Item" data-ng-click="AddNewItem()" />
            </div>
        </div>
</body>
</html>

The json content is not being loaded correctly to repeat them instantly...No action is taking place..

Answer №1

It's my belief that utilizing something along the lines of this code snippet is more effective for returning values in a service:

Item.factory("ItemsFactory", function(){

 var items = [
    { name : "Washing Powder",
    price : "2000",
    balance : 14
    },

    { name : "Shampoo",
      price : "8500",
      balance : 03
    },

    { name : "Soap",
      price : "1850",
      balance : 27
    }
];

return {
   getItems: function(){
    return items;
   },

postItems:function(){

}
});

In addition, I also believe that:

 factory.getItems() = function(){}

is inaccurate and the proper syntax should be:

 factory.getItems = function(){}

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

Achieving a full-height div using CSS and HTML to fill the remaining space

Here is the current layout structure I am working with: div { border: 1px solid } <div id="col_1" style="float:left;width:150px;">1</div> <div id="col_2" style="float:left;width:100px;">2</div> <div id="col_3" style="float:l ...

Exporting modules/namespaces to the window object in TypeScript

I have experience building APIs and applications in ES2015, but I am still learning the best practices for TypeScript. Can someone assist me with this challenge? Suppose I am creating an API/SDK for a shop. The objective is for the user to include my js f ...

How can you effectively retrieve values in Chakra Core without encountering any memory complications?

I have been studying this example in an effort to develop a basic JavaScript engine that can execute scripts like the zxcvbn library. I thought I had it all figured out, but there are certain parts of the code that still puzzle me. Particularly, I am strug ...

Images set as the og:image on the following 14 websites hosted on Vercel require authentication to be displayed

After deploying my Next.js 14 site on Vercel, I placed opengraph-image.png in the app folder alongside layout.tsx. Upon inspecting the meta tag, I noticed the following: <meta property="og:image" content="https://ns-website-6pnvd8ili-mare ...

Creating personalized hooks that rely on React query requests

Utilizing a series of custom hooks, I am able to fetch data and perform various calculations based on that data. One particular hook calculates the total amount that should be set aside monthly for future expenses, using the output from previous data-fetch ...

What is the best way to choose the following 3 elements that are siblings of a randomly positioned element?

I need assistance with selecting the next three siblings of a grid of divs on a board. Although I considered using nextUntil(), the issue is that the ids of these siblings are randomly generated upon loading, so they are not fixed. I am unsure how to solve ...

What is the best way to create a basic accordion using only certain table rows?

I am faced with the task of transforming a HTML table that lists various items. Each <tr> within the table contains a unique title element, but there are cases where rows can share the same title indicating their relation. My goal is to implement jQu ...

Encountering "net::ERR_EMPTY_RESPONSE" error when making a HTTP PUT request using the HUE API in JavaScript

GET requests are functioning properly. PUT requests made from the API Debug tool are also working correctly. However, both PUT and POST requests, regardless of the data or API URL used, are resulting in the following error: example: OPTIONS net::ERR_ ...

Converting an XML response into JSON format

I have encountered a challenge while working on a project that involves making an API request. Upon posting a JSON request to the server, I receive an XML response like this: "<response> \r\n <data> \r\n ...

Creating a Gatsby blog post on Enhancing Your Website with Rich Snippets for Embedded YouTube Videos

I have a website built with Gatsby and the Netlify CMS, and occasionally I want to include embedded YouTube videos in my blog posts. I am looking to implement a videoObject schema for these videos with the following structure: { "@context": "http:// ...

Unable to upload photo using Ajax request

I am in the process of trying to utilize Ajax to upload an image, so that it can be posted after the submit button is clicked. Here is the flow: User uploads image -> Ajax call is made to upload photo User clicks submit -> Post is shown to the user ...

Update a script that handles input float labels to support textarea elements as well

I am looking to modify a float label script that currently works for input boxes in order to make it work for textareas. I attempted to add $fields.on("textarea", floatLabel) to the script but it did not produce the desired result. Any suggestions or assis ...

What is the best way to iterate through a JSON object using the stages array provided?

I am facing an issue with parsing the provided json to display the desired output on the screen. These are the steps I need to follow for parsing this json: 1. Extract the stages array from the json - for example, stages ["check_dependency_progress", "sh ...

Utilizing Asp.net MVC to trigger a C# method from the client-side using an onclick JavaScript event

In my project, I have a "MultiLanguageProvider" class in C#. This class is not a Controller or Model. The goal is to have a functionality where when a user clicks on <a href="">Change language</a>, it should trigger the server-side method void ...

Is there a way to control the playback of a video, such as

Currently, I am involved in a project related to IPTV. One of my objectives is to be able to capture the moment at which a video is paused so that when clicking on another button, a small iframe opens with the same video continuing from where it was origin ...

Retain the input values even after the page is refreshed

I have developed a simple form validation page in ReactJS. The input fields are validated using regex patterns. One issue I encountered is that if I enter data in the input fields and refresh the page before completing the form, the input fields are clear ...

`req.user` seems to be unresolved, but it is actually defined

Currently, I am working on developing an Express.js application that utilizes Passport.js for authentication in an administration panel. The program is functioning correctly at the moment, with my app.js initializing passport and setting up sessions proper ...

Steps to achieve a fully expanded sidenav using Angular Material

Currently, I am utilizing Angular-Material and have successfully integrated a SideNav menu into my project. However, there is an issue with the menu’s appearance based on screen size. When the screen is small, the menu remains hidden until the Menu toggl ...

Using lodash to combine the values of identical objects

As a newcomer to development, I am looking to group similar objects within an array of JSON objects. Here is an example of my JSON array: var data = [ { zone: "Bottom", group: "Bottom girders", original: 7, ...

Retrieving data from a collection with the find() method in a custom date format

Schema for Customer Data Customers.js import mongoose from 'mongoose'; const Customers = mongoose.Schema({ CustomerID: { type: String, default: "" }, Name: { type: String, default: "" }, Email: { type: String, default: "" }, Pho ...