Service, Factory, Provider

http://angularjs.org/

by Matthew Vasallo

HTML

<script src="http://code.angularjs.org/angular-1.0.0.js"></script>
<div ng-controller="MyCtrl">TEST 1 => {{hellos}}
</div>
<div ng-controller="TestCtrl">TEST 2 => {{byes}}</div>
<div ng-controller="MyCtrl">TEST 1 => {{hellos}}

JavaScript

var myApp = angular.module('myApp', []);

//service style, probably the simplest one
myApp.service('helloWorldFromService', function testing() {
    console.log('loading service');
    var count = 1;
    testing.prototype.sayBye = function () {
        return "good bye!";
    };
    this.sayHello = function () {
        count++;
        return "Hello, World!" + count;
    };
});

//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function () {
    return {
        sayHello: function () {
            return "Hello, World!"
        }
    };
});

//provider style, full blown, configurable version     
myApp.provider('helloWorld', function () {

    this.name = 'Default';

    this.$get = function () {
        var name = this.name;
        return {
            sayHello: function () {
                return "Hello, " + name + "!"
            }
        }
    };

    this.setName = function (name) {
        this.name = name;
    };
});

//hey, we can configure a provider!            
myApp.config(function (helloWorldProvider) {
    helloWorldProvider.setName('Mateo');
});


function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {

    $scope.hellos = [
    helloWorld.sayHello(),
    helloWorldFromFactory.sayHello(),
    helloWorldFromService.sayHello(),
    helloWorldFromService.sayBye()];
}
        
function TestCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {

    $scope.byes = [
    helloWorld.sayHello(),
    helloWorldFromFactory.sayHello(),
    helloWorldFromService.sayHello(),
    helloWorldFromService.sayBye()];
}