AngularJS set var: http get

I have an angular filter that works fine:

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;
                }
            };
        }); 

But the var categories and var products are still hardcoded, so I want to get the data I need from my server to populate these variables. And I can’t get it right? I have another function where I can get the required data, but I don’t know how I can get these 2 in 1 ...?

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];
        }
});
});

So, how can I set var categories correctly in the required $ http.get file to return my server data to the filter above?

+4
source share
1 answer

I think you can get rid of the hard-coded block in the service and just return:

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

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

Make sure you have configured the services for the service (i.e. $http) correctly :

.factory('store', function ($http) {
    // The above return block here
});

And that should do the trick!

+2
source

All Articles