Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - different ways to create controllers and services, why?

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";
}
like image 758
Neil Avatar asked Jan 06 '13 17:01

Neil


People also ask

What is controller and service in AngularJS?

In AngularJS, a Controller is defined by a JavaScript constructor function that is used to augment the AngularJS Scope. Controllers can be attached to the DOM in different ways.

Why are controllers used in AngularJS?

AngularJS controllers are used to control the flow of data of AngularJS application. A controller is defined using ng-controller directive. A controller is a JavaScript object containing attributes/properties and functions.

Can you create controller in AngularJS?

In AngularJS, a controller is defined by a Javascript construction function, which is used in AngularJS scope and also the function $scope) is defined when the controller is defining and it returns the concatenation of the $scope. firstname and $scope. lastname.


1 Answers

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.

like image 164
asgoth Avatar answered Oct 14 '22 06:10

asgoth