1

I am trying to run a foreach against a resource via a controller in order to output each of the items in the JSON array (later I will add conditionals), but it is returning as "undefined":

 pfcControllers.controller('pfcArticlesCtrl', ['$scope', '$log', 'pfcArticles', function ($scope, $log, pfcArticles) {
$scope.articlecount = pfcArticles.query();

var val = [];

angular.forEach($scope.articlecount, function (value, key) {
    this.push(value);
}, val);
    console.log(val);
    $scope.temp = val;

}]);

However, if I create a static array as follows, it works as expected:

pfcControllers.controller('pfcArticlesCtrl', ['$scope', '$log', 'pfcArticles', function ($scope, $log, pfcArticles) {
$scope.articlecount = pfcArticles.query();

articlz = [{ title: 'art1', id: 1}]

var val = [];
// Look over categories
angular.forEach(articlz, function (value, key) {
    this.push(value);
}, val);
    console.log(val);
    $scope.temp = val;

}]);

Here is my resource:

    pfcServices.factory('pfcArticles', ['$resource', function ($resource) {
    return $resource('https://myrestcall.net/tables/articles', {},
    {
        'update': { method: 'PATCH' }
    }
    );
}]);

What I believe is happening is that my foreach is executing before the JSON is returned since it is most likely async. How do I have it wait until my JSON is ready to be looped?

1 Answer 1

1

You're looking for something like the following:

pfcControllers.controller('pfcArticlesCtrl', ['$scope', '$log', 'pfcArticles', function ($scope, $log, pfcArticles) {
    var articles = pfcArticles.query(function() {
        $scope.articlecount = articles.length;
        var val = [];

        angular.forEach(articles, function (value, key) {
            this.push(value);
        }, val);

        $scope.temp = val;
    });
}]);

The reason you are logging undefined is because the call to query() is asynchronous. You need to specify what to do with the articles in the resolve handler for the query.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.