Convert an Angular function to service

I have the following function that I'd like to convert to a service.

How would I go extracting the $resource call into an angular service, and how would I call this service?

self.select = function (email) {
    var Player = $resource('/player/get',{email:email});
    var player = Player.get(function() {
        self.selectedPlayer.email = player.email;
        self.selectedPlayer.fuel = player.fuel;
        self.selectedPlayer.cargo = player.cargo;
        self.selectedPlayer.food = player.food;
    });
}

Thanks!

I suspect that you are working off version 0.9.19. I would first suggest that you move over to version 1.0rc4. Version 1.0 is close to going live and is stable but it has many breaking changes over version 0.9. You can see the Angular documentation for more information.

In v1.0 you wrap everything in a module: controllers, services, directives and so on. Create a module like so:

var module = angular.module('ModuleName', ['ngResource']);

In version 1.0 the resource service is factored out into its own class, so you have to give it as a dependency. You will also have to include the resource js file in your app.

Now to create a service you can simply use the module API. In this case:

module.factory('Player', ['$resource', function($resource) {
   return $resource('/player/get');}]);

Notice here that the dependency on $resource is injected by angular.

Personally I don't like to mess with the scope inside my service so I would have the following inside my controller:

module.controller('MyController', ['$scope', 'Player', function($scope, Player) {
    $scope.select = function(email) {
        console.log("selecting");
        Player.get({
        email: email
        }, function(player) {
            $scope.selectedPlayer = player;
        });
    };
}]);​

Notice that in v1.0 the scope is also injected into the controller so no using self any more. Also I took the liberty of assuming that the selectedPlayer would only contain the fields from player so I just wrote player straight over the top of selectedPlayer. You could also do it field by field manually or use angular.extend($scope.selectedPlayer, player); to merge the two objects.

Here is a fiddle: http://jsfiddle.net/DukvU/

angular.module('myModule', []).
  factory('Player', function($resource) {
    return $resource('/player/get',{email:email});
  });

function MyController($scope, Player) {
   $scope.select = function(email) {
     Player.get(....);
   }
}