Factory vs Service

angularjs factory vs service do the same thing, just a different way of instantiation

by mslocum

HTML

<div ng-controller="Ctrl">
    <p>Number of resolves: {{ iResolves }}</p>
    <p>Number of notifies: {{ iNotifies }}</p>
    <p ng-repeat="strMessage in aFromService">{{strMessage}}</p>
</div>

JavaScript

//angular.js example for factory vs service
var app = angular.module('myApp', []);
    
app.service('testService', ["$q", "$interval", function($q, $interval){
    this.getArray = function(){
        var oRetval = [],
            oDeffered = $q.defer(),
            i = 0;
        
        $interval(function() {
            var strData = 'Data from service ' + i++;
            oRetval.push(strData);
            oDeffered.notify(strData);
            //oDeffered.resolve(strData);
        }, 1000);
        
        oRetval.$promise = oDeffered.promise;
        return oRetval;
    };        
}]);

function Ctrl($scope, testService)
{
    $scope.iResolves = 0;
    $scope.iNotifies = 0;
    $scope.aFromService = testService.getArray();
    
    $scope.aFromService.$promise.then(function() {
        $scope.iResolves++;
    }, null, function() {
        $scope.iNotifies++;
    });
}