Different syntax in Angular for controller, services and others

What's the difference between

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

and

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

Even though both give the same result and no error. Actually the first makes the code clean and less to write. It also refers to services, directives. Can someone give me some info about this.

+5
source share
2 answers

There is no functional difference. Using .controller('ctrl',['$scope', function($scope){...} - allow the correct reading of the mini version.

Minimization Note - AngularJS

Since Angular determines the dependencies of the controller on the argument names of the controller constructor function, if you want to minimize the JavaScript code for the MyCtrl controller, all its function arguments will also be minimized, and the injector will not be able to correctly identify the services.

We can overcome this problem by annotating a function with dependency names provided as strings that will not be minimized. There are two ways to provide these annotations for injection:

  • Create the $ injection property for a controller function that contains an array of strings. Each line in the array is the name of the service that you need to enter for the corresponding parameter:

     function MyCtrl($scope, $http) {...} MyCtrl.$inject = ['$scope', '$http']; app.controller('MyCtrl', MyCtrl); 
  • Use the built-in annotation in which, instead of providing a function, you provide an array. This array contains a list of 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 introduced using Angular, so before your project style guide you can decide which one you use.

When using the second method, as a rule, when creating a controller, the inline constructor function is usually provided as an anonymous function:

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

Adding wzVang to the response. You can follow your syntax. iee

 .controller('ctrl', function($scope){ }); 

no problem. It is readable. But you must minimize the code during production. Then you can use ngAnnotate .

0
source

All Articles