Using service factories

A service factory is the simplest general purpose service type that allows you to use the singleton nature of AngularJS services with encapsulation.

How to do it…

The service factory's return value is what will be injected when the factory is listed as a dependency. A common and useful pattern is to define private data and functions outside this object, and define an API to them through a returned object. This is shown in the following code:

(app.js) angular.module('myApp', []) .controller('Ctrl', function($scope, MyFactory) { $scope.data = MyFactory.getPlayer(); $scope.update = MyFactory.swapPlayer; }) .factory('MyFactory', function() { // private variables and functions var player = { name: 'Peyton Manning', number: 18 }, ...

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.