Factory vs Service

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

by mslocum

HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<div ng-controller="Ctrl as C">
    <button ng-click="C.doStuff()">Do Stuff</button>
    <p>Value: {{ C.oValue.val }}</p>
    <div my-dir></div>
</div>

JavaScript

var app = angular.module('myApp', []);
    
app.directive('myDir', function($compile){
    return {
        link: function(scope, el, attrs) {
            el.append(
                $compile( '<div class="widget-stuff" gl-widget-stuff data-widget="C.oValue"></div>' )( scope )
            );
        }
    }
});


app.directive('glWidgetStuff', function(){
    return {
        scope: {
            widget: "=widget"
        },
        template: '<input type="text" ng-model="widget.val"/>'
    }
});

app.service('dataService', ["$q", "$interval", function($q, $interval){
    this.getData = function(){
        var oRetval = [2, 4, 6],
            oDeffered = $q.defer();
        
        $interval(function() {
            oDeffered.notify({
                val: 3
            });
            //oDeffered.resolve(strData);
        }, 1000);
        
        return oDeffered.promise;
    };
}]);



function Ctrl($scope, dataService)
{
    var that = this;
    this.oValue = {
        val: 0
    };
    
    this.doStuff = function() {
        this.oValue.val++;
    };
    
    dataService.getData().then(null, null, function(oData) {
        //that.oValue = oData;
        angular.extend(that.oValue, oData)
    });

}