Using services

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.

How to do 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 ...

Get AngularJS Web Application Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.