Skip to content Skip to sidebar Skip to footer

Accessing Objects Returned From A Factory

So I have a factory that fetches objects from a server: .factory('Articles', function($http) { var articles = []; return { all: function(){ $http.get('htt

Solution 1:

I think that your problem may be related to promises. Bear in mind that when you use $http you're creating promises and you should use the corresponding callbacks when using the return data.

In the service you're already using .then method, but you aren't actually returning anything from the service to the controller. You should return the generated promise and use the .then/.error methods to update your $scope variable.

.factory('Articles', function ($http) {
    var articles = [];
    return {
        all: function () {
            return $http.get("http://jsonp.afeld.me/?url=http://examplesite.com/page.html?format=json").then(function (response) {
                articles = response.data.items;
                console.log(response.data.items);
                return articles;
            });
        },
        get: function (articleId) {
            for (var i = 0; i < articles.length; i++) {
                if (articles[i].id === parseInt(articleId)) {
                    return articles[i];
                }
            }
            returnnull;
        }
    }
});

And in your controller

.controller('GautengCtrl', function ($scope, $stateParams, Articles) {
    $scope.articles = [];
    Articles.all().then(function(data){
        $scope.articles = data;
    });
})

Post a Comment for "Accessing Objects Returned From A Factory"