Angular.js - callback needed using service

Problem

I have a setup with a service to fetch a list of items, a controller to do something to that list, and a view to iterate through and display each item.

Thing is, my items are links to RSS feeds and in the controller I want to parse through these RSS feeds and set up the model data for the view to handle.

Now, there are some more modifications to the modelling to be done (I need to model the actual RSS feed content), but my first problem is that the data fetched by the service is not modifiable in my controller (since the call hasn't finished, at the time I try to access it, I guess). Basically it's just an empty array if i write it to the console.

So I'd need to know how to trigger the data operations in the controller once the service call has finished.

Thanks!! // Joakim

Service code:

angular.module('itemfeedServices', ['ngResource']).
factory('Item', function($resource){
    return $resource('items/:itemId.json', {}, {
        query: {method:'GET', params:{itemId:'items'}, isArray:true}
    });
 });

Controller code:

function ItemListCtrl($scope, Item) {
  $scope.items = Item.query();
  console.log($scope.items); // gives []
 }
Problem courtesy of: joakimnorberg

Solution

Basically, I think you want a callback? The documentation says:

The action methods on the class object or instance object can be invoked with the following parameters:

    HTTP GET "class" actions: Resource.action([parameters], [success], [error])
    non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
    non-GET instance actions: instance.$action([parameters], [success], [error])

Here

So, using:

Item.query({}, function() {
//you callback
});

should work.

Solution courtesy of: mael

Discussion

While callbacks will work, it's not the Angular way to do it. Check out the promises pattern and Angular own implementation of it, $q

Discussion courtesy of: bluehallu

This recipe can be found in it's original form on Stack Over Flow.