Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different syntax in Angular for controller, services and others

What is the difference between

app.controller("MyCtrl", function($scope, $http){
    //...
});

and

app.controller("MyCtrl", ["$scope", "$http", function($scope, $http){
    //...
}]);

Even though both gives the same result and no error. In fact the first one makes code clean and less to write. Also it is same in services, directive. Can someone give me a small brief about it.

like image 442
Atul Verma Avatar asked Oct 31 '22 02:10

Atul Verma


1 Answers

No functional difference. Using .controller('ctrl',['$scope', function($scope){...} is to allow a minified version to be read correctly.

A Note on Minification - AngularJS

Since Angular infers the controller's dependencies from the names of arguments to the controller's constructor function, if you were to minify the JavaScript code for MyCtrl controller, all of its function arguments would be minified as well, and the dependency injector would not be able to identify services correctly.

We can overcome this problem by annotating the function with the names of the dependencies, provided as strings, which will not get minified. There are two ways to provide these injection annotations:

  1. Create a $inject property on the controller function which holds an array of strings. Each string in the array is the name of the service to inject for the corresponding parameter:

    function MyCtrl($scope, $http) {...}
    MyCtrl.$inject = ['$scope', '$http'];
    app.controller('MyCtrl', MyCtrl);
    
  2. Use an inline annotation where, instead of just providing the function, you provide an array. This array contains a list of the service names, followed by the function itself:

    function MyCtrl($scope, $http) {...}
    app.controller('MyCtrl', ['$scope', '$http', MyCtrl]);
    

Both of these methods work with any function that can be injected by Angular, so it's up to your project's style guide to decide which one you use.

When using the second method, it is common to provide the constructor function inline as an anonymous function when registering the controller:

app.controller('MyCtrl', ['$scope', '$http', function($scope, $http) {...}]);
like image 173
Walter Chapilliquen - wZVanG Avatar answered Nov 15 '22 07:11

Walter Chapilliquen - wZVanG