Chapter 2: Using service providers

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

// -providers are parent of service and provider
//    they are the only service that allows you to 
//    during config also, inspect and modify other service types
// - obj with get method is injected after init: 2nd return
// - the obj wraping the obj with the get is what is injectec into
//   the config phase: 1st return

angular.module('myApp', [])
.config(function(PlayerProvider) {
    // appending 'Provider' to the injectable 
    // is an Angular config() provider convention
    PlayerProvider.configSwapPlayer();
    console.log(PlayerProvider.configGetPlayer());
})
.controller('Ctrl', function($scope, Player) {
    $scope.data = Player.getPlayer();
    $scope.update = Player.swapPlayer;
})
.provider('Player', function() {
    var player = {
        name: 'Aaron Rodgers',
        number: 12
    },  swap = function() {
        player.name = 'Tom Brady';
    };
    
    return {
        configSwapPlayer: function() {
            player.name = 'Andrew Luck';
        },
        configGetPlayer: function() {
            return player;
        },
        $get: function() {
            return {
                getPlayer: function() {
                    return player;
                },
                swapPlayer: function() {
                    swap();
                }
            };
        }
    };
});