AngularJS variable assignment with HTTP GET operation

The angular filter I have set up is functioning perfectly:

categorieFilter = angular.module("categorieFilter", [])
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
    $scope.search = "";
    $scope.products = [];
    $scope.categories = [];

    $scope.categories = store.getCategories();
    $scope.products = store.getProducts();

    $scope.filterProductsByCats = function(category){
        $scope.search = category;
    };
}])
categorieFilter.factory('store', function(){
            var categories = ['Lattes','CC Blend','Frappes'];
            var products = [
                {name: 'Latte machiatto',category: 'Lattes'},
                {name: 'Frappe ice',category: 'Frappes'},
                {name: 'Latte caramel',category: 'Lattes'},
                {name: 'Frappe speculoos',category: 'Frappes'},
                {name: 'Cappucino',category: 'CC Blend'},
                {name: 'Filter coffee',category: 'CC Blend'},
            ];
            return {
                getCategories : function(){
                    return categories;
                },
                getProducts : function(){
                    return products;
                }
            };
        }); 

However, the variables categories and products are hardcoded. I aim to retrieve this information from my server. Despite having another function that can fetch the necessary data, integrating them remains a challenge for me.

categories = angular.module('categories', []);
categories.controller("category",function($scope, $http){
    var serviceBase = 'api/';
    $http.get(serviceBase + 'categories').then(function (results) {
        $scope.categories = results.data;
        for(var i = 0; i < $scope.categories.length; i++){
            var categories = $scope.categories[i];
        }
});
});

How can I correctly bind the variable categories to the $http.get request in order to populate my filter with server data?

Answer №1

If you want to improve the service, consider removing the hard-coded block and returning the following instead:

return {
    getCategories: $http.get('/categories').success(function (data) {
        return data;
    }),
    
    getProducts: $http.get('/products').success(function (data) {
        return data;
    })
}

Ensure that your dependencies are properly set up for the service, like $http:

.factory('store', function ($http) {
    // The code block above should be placed here
});

This adjustment should work effectively!

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

Why is the reference of `this` pointing to `o` in this scenario (o.method)() rather than the global object?

Let's consider the scenario with an object: var o = { prop: 3, method: function() {return this.prop} } My expectation was that calling (o.method)() would result in undefined, but instead it returned 3, indicating that the reference of this ...

Can anyone recommend a speedy sorting algorithm for an extensive list of objects in JavaScript?

Struggling to organize a large array of 2000 elements in ReactJS using JavaScript. The array includes: data = [ { index: 0, id: "404449", product_name: "ette", brand_name: "Dyrberg/Kern", base_pri ...

Form a bond with the latest SignalR library to initiate communication

After attempting to connect to an asp.net core signalR server using the code below, I encountered some issues. Can you spot where I might have gone wrong? Here is the error message that I received: Error: The "promise" option must be a Promise v ...

Troubleshooting problem with Shopify mailto tag

I am facing an issue with external links in my Shopify store. My app injects a script to display a bubble with an anchor tag that redirects users to a specified link. However, Shopify is altering the anchor tag to a different link, resulting in a 404 erro ...

Retrieving a MAC address from a device using a web script or HTTP protocol

Is it feasible, with access to all end user devices, to request the device's MAC address using web scripting in Apache/IIS/Nginx? Would PHP, Perl, or ASP be able to accomplish this task? The client devices run on iOS, so the method described here wil ...

Tips on utilizing ajax to load context without needing to refresh the entire page

As a beginner in AJAX, I have some understanding of it. However, I am facing an issue on how to refresh the page when a new order (order_id, order_date, and order_time) is placed. I came across some code on YouTube that I tried implementing, but I'm n ...

Uploading several files at once with Angular

I find myself in a scenario where I need to work with a form that contains multiple rows, each consisting of two text field entries and a file upload option. There can be any number of these rows ('N'). In addition, there is a master file that ap ...

Processing the retrieved object from Dropbox API using Node.js and Express

I've been attempting to carry out a simple task like uploading a file to Dropbox. The file uploads successfully, but I'm in need of the response that contains details such as the file name, size, and path. I understand that I'm getting lost ...

How do I prevent a specific word from being removed in a contenteditable div using JavaScript?

Attempting to create a terminal-like experience in JS, I am looking to generate the word 'current source, current location' (e.g., admin@ubuntuTLS~$: ~/Desktop) at the beginning which cannot be removed. Also, I want to prevent the caret from bein ...

A guide to retrieving the timezone based on a specific address using the Google API

I need to utilize the Google API time zones, which requires geocoding the address to obtain the latitude and longitude for the time zone. How can I achieve this using a value from a textarea? Here are the 2 steps: Convert the textarea value into a geoc ...

What is the best way to apply custom styles in reactJs to toggle the visibility of Google Maps?

There are three radio buttons that correspond to school, restaurant, and store. Clicking on each button should display nearby locations of the selected type. Displaying Google Map and nearby places individually works fine without any issues. class Propert ...

What techniques can I implement to optimize the speed of this feature in JavaScript?

I have developed a feature that highlights any text within a <p> tag in red based on a user-specified keyword. The current implementation works well, but it is slow when dealing with over 1000 lines of <p>. Is there a faster way to achieve this ...

With the power of jQuery, easily target and retrieve all label elements within a specified

Currently, I'm working on developing a function that should be executed whenever any of the labels for a particular group of radio buttons are clicked. So, I need a way to reference all the labels in this radio button group. In my search for a soluti ...

Arranging currency values in Angular's UI-Grid widget

Need help sorting a grid column with dollar values that include $ and , as the sorting is not functioning correctly. Is there a solution to make the sorting work, or should I convert the values to numbers and then display them as money? Here is what I cur ...

JavaScript Equivalent of jQuery's removeClass and addClass Functions

I am faced with the challenge of rewriting the following code without using jQuery: document.querySelector('.loading-overlay').classList.remove('hidden'); Can anyone provide guidance on how this can be achieved? ...

Fully responsive header designed for optimal experience at any screen height

I am facing issues with the header and cannot seem to find a solution. My goal is to make the header span 100% of the window screen height. I need a responsive header that adjusts to 100% height, and when resizing for a smaller viewport, nothing should sho ...

What are some ways to accomplish this task without relying on a photo editing tool?

Is it possible to swap the image link: with this new link: without having to use a photo editor? Below is the CSS and HTML code: I was unable to upload the logo due to the restriction of needing at least 10 reputation points in order to post more t ...

Exclude the UL hierarchy from removing a class in jQuery

Check out this fiddle to see the code snippet: http://jsfiddle.net/3mpire/yTzGA/1/ I am using jQuery and I need to figure out how to remove the "active" class from all LIs except for the one that is deepest within the hierarchy. <div class="navpole"&g ...

Bidimensional Selenium matrix

Could someone please help me understand how to extract values from a bi-dimensional array using Selenium? I have a resources.js file with the array created, and need to access it in Selenium. Here is the structure of the array: The array consists of 4 col ...

XMLHttpRequest Refusing to Send Data

This snippet of code is crucial for the custom extension: let url = "https://mywebsite.com/data.php"; function sendRequest() { var client = new XMLHttpRequest(); client.open("POST", url, true); client.setRequestHeader("Content-Type", "text/pla ...