19

I keep seeing different examples of creating controllers and services in AngularJS and I'm confused, can anyone explain to me the differences between the two approaches?

app.service('reverseService', function() {
    this.reverse = function(name) {
        return name.split("").reverse().join("");
    };
});

app.factory('reverseService', function() {
    return {
        reverse : function(name) {
            return name.split("").reverse().join("");
        }
    }
});

And also a controller example:

function ExampleCtrl($scope) {
    $scope.data = "some data";
}

app.controller("ExampleCtrl", function($scope) {
    $scope.data = "some data";
}
3

2 Answers 2

20

The first one will pollute the global namespace, which is not what you want in the long run.

function ExampleCtrl($scope){
    $scope.data = "some data";
}

The second one scopes the Controller to that module instance. It makes it also injectable. Better still is using the array notation (as below), since this will survive minification.

app.controller("ExampleCtrl", ['$scope', function($scope){
    $scope.data = "some data";
}]);

The difference between an (angular) service and factory seems quite small. A service wraps a factory, which uses $injector.instantiate to initialize the service.

Sign up to request clarification or add additional context in comments.

1 Comment

How can you add Factories on the parameters?
0

My preferred way of creating controllers and directives is as following:

/**
* SomeCoolModule.controller.js
*/

(function(){
'use strict';

    angular.module('app.modals.SomeCoolModule').controller('SomeCoolModuleController', SomeCoolModuleController);

    AddFlowCurveModalController.$inject =
        [
            '$scope',
            '$filter',
            '$log',
        ];

    function SomeCoolModuleController($scope, $filter, $log) {
        /* controller body goes here */
    }
})();

PS: no global namespace pollution is taking place above due to IIFE.

1 Comment

I do the same with services also :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.