Chapter 2: Using services

by billy roberts

HTML

<script src="https://code.angularjs.org/1.3.2/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="Ctrl">
        <button ng-click="update()">Update</button>
        {{ data.name }} #{{ data.number }}
    </div>
</div>

JavaScript

// service indistinguishable from service.factory from scope.
// the difference is that the controller is injected - this
// means you must use 'this' to define your methods.

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();
    };
});