2

I'm newbie to angular JS. I had faced two different type of controller declarations which I'm unable to understand its impact behind the scene.

vmyApp.controller('GreetingController', ['$scope', function($scope) {
 $scope.greeting = 'Hola!';
}]);

From the above snippet I understood they had taken a function in dependency of controller with 2 parameters one as '$scope' and other with function.

Other snippet as follows :

vmyApp.controller('GreetingController', function($scope) {
  $scope.greeting = 'Hola!';
});

Here direct function as 2nd parameter to controller without any dependency.

Please explain me the differences of its impact.

Ram
  • 3,887
  • 4
  • 27
  • 49
Srikanth Reddy
  • 117
  • 2
  • 9

2 Answers2

3

They serve the same function, except the top controller is what you should use if you're going to minify your code. AngularJS uses parameter names to inject the values to your controller function. In JavaScript minification process, these parameters are renamed to shorter strings. By telling which parameters are injected to the function with a string array, AngularJS can still inject the right values when the parameters are renamed.

Kyle Krzeski
  • 6,183
  • 6
  • 41
  • 52
1

Nothing really different when running your AngularJS application.

However, when you will try to compile it with a task runner (Gulp, Grunt or others), the second one will break your application, because $scope will be replaced.

String are not replaced in minif and uglify process, this is why you need to inject dependencies as string.

This guidestyle explain why you should do the second one.

Zooly
  • 4,736
  • 4
  • 34
  • 54