Book Image

AngularJS Web application development Cookbook

By : Matthew Frisbie
Book Image

AngularJS Web application development Cookbook

By: Matthew Frisbie

Overview of this book

Packed with easy-to-follow recipes, this practical guide will show you how to unleash the full might of the AngularJS framework. Skip straight to practical solutions and quick, functional answers to your problems without hand-holding or slogging through the basics. Avoid antipatterns and pitfalls, and squeeze the maximum amount out of the most powerful parts of the framework, from creating promise-driven applications to building an extensible event bus. Throughout, take advantage of a clear problem-solving approach that offers code samples and explanations of components you should be using in your production applications.
Table of Contents (17 chapters)
AngularJS Web Application Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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
  },  swap = function() {
    player.name = 'A.J. Green';
  };
  // public API
  return {
    getPlayer: function() {
      return player;  
    },
    swapPlayer: function() {
      swap();
    }
  };
});

Since the service factory values...