1

I've seen 2 types of controllers definition:

angular.module('myApp.controllers',[])
  .controller('MainCtrl', ['$scope'], function($scope){
   //controller code
}

And a simple:

function MainCtrl($scope) {
  //controller code
}

What's the different? Which one is the preferred one?

Gal Bracha
  • 16,762
  • 11
  • 64
  • 81

1 Answers1

2

The difference is that the first is a controller inside the module. The second method is a controller on the global ( on the Window object! ).

Like you would have heard already, polluting the global object is a bad idea. Hence, the second method is not preferred (But is used for quick prototyping to show off a feature easily and is easier to type. So this one is used in pretty much all examples.)

The first way, i.e

angular.module('myApp.controllers',[])
  .controller('MainCtrl', ['$scope'], function($scope){
   //controller code
}

is the preferred way and should be used in all for production applications.

ganaraj
  • 26,809
  • 6
  • 62
  • 59