Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

The different ways of setting up a Controller in Angular.

Hi Guys,

I've recently finished the Angular JS course here on Treehouse (got a bit lost here and there but think I have a pretty firm grasp), and I really like what it has to offer.

I decided to do a bit of research, find some example projects etc and came across something that confused me a bit.

When setting up a controller, Huston showed us this way:

app.controller('MainController', function($scope) { 
  $scope.thing = 'stuff here'; 
});

However I've seen it written this way:

app.controller('MainController', ['$scope', function($scope) { 
  $scope.thing = 'more stuff here'; 
}]);

I understand what's going on in the first example, but can't understand what that Array is doing in the second! Is the latter an older version's way of handling the controller/is there any advantage to either way?

Thanks,

Tayler

1 Answer

Paul Ryan
Paul Ryan
4,584 Points

it is to do with minification.

if your first example was minified, your code would no longer work as the $scope parameter would be changed to something like 'e' so angular wouldn't inject the $scope object.

This would not be the case in the second example as you are defining your dependencies as an array and these will not the minified as they are represented as strings. Strings do not get minified.

Using something like gulp you can get around this problem and use the first approach.

I hope my answer makes sense. Here is a link also: http://stackoverflow.com/questions/30088534/reason-for-using-array-notation-when-defining-angularjs-controller