Question

In one of my controller functions in my angular.js application, I'm trying to use Google's RSS Feed API to fetch feed entries to populate in my scope.items model.

It's behaving quite strangely, with the console output in the innermost part always being '2' but while the console output in the outermost loop being '0' and '1' (which is correct since that is the length of my items array).

I'm thinking it could have something to do with the Google API thing being an async request and that it hasn't finished before I try to manipulate it (?). Still doesn't make sense that my iterator variable would become '2' though!

Code:

function ItemListCtrl($scope, Item) {
$scope.items = Item.query({}, function() { // using a JSON service
    for (var i = 0; i < $scope.items.length; i++) { // the length is 2 here.
        $scope.items[i].entries = [];
        console.log(i); // gives '0' and '1' as output in the iterations.
        var feed = new google.feeds.Feed($scope.items[i].feedUrl);
        feed.load(function(result) {
            console.log(i); // gives '2' as output in both the iterations.
            if (!result.error) {
                for (var j = 0; j < result.feed.entries.length; j++) {
                    $scope.items[i].entries[j] = result.feed.entries[j];
                }
            }
        });
    }
});

}

Was it helpful?

Solution

The callback function is executed asynchonously, after the loop over the items has ended. And at the end of the loop, i is equal to 2, since there are 2 items in your items array.

See Javascript infamous Loop issue? for another example of the same behavior, and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Creating_closures_in_loops.3A_A_common_mistake for an more in-depth explanation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top