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 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 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()"&gt...