Services act in much the same way as service factories. Private data and methods can be defined and an API can be implemented on the service object through it.
A service is consumed in the same way as a factory. It differs in that the object to be injected is the controller itself. It can be used in the following way:
(app.js) angular.module('myApp', []) .controller('Ctrl', function($scope, MyService) { $scope.data = MyService.getPlayer(); $scope.update = MyService.swapPlayer; }) .service('MyService', function() { var player = { name: 'Philip Rivers', number: 17 }, swap = function() { player.name = 'Alshon Jeffery'; }; this.getPlayer = function() { return player; }; this.swapPlayer = function() { swap(); }; });
When bound to $scope
, the service interface is indistinguishable from a factory. This is shown here:
(index.html) <div ng-app="myApp"> <div ng-controller="Ctrl"> <button ng-click="update()">...