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

Igor Yamshchykov
Igor Yamshchykov
24,397 Points

What is the best way to organize my code in AngularJs controllers?

I saw different ways of organizing code inside controllers, now my question is about functions and how should I organize them properly.

(function() {
angular
.module('myModule')
.controller('myCtrl',myCtrl);

function myCtrl() {
    $scope.someFunction = someFunction;

     function someFunction() {
          //some actions here
     }
}
})();

or

(function() {
angular
.module('myModule')
.controller('myCtrl',myCtrl);

function myCtrl() {
    $scope.someFunction = function () {
          //some actions here
     }
}
})();

which of those two is better way to organize the code ?

Or maybe there's some completely different way to do this, that is considered as best practice ? I will appreciate any of your answers. Thank you!

1 Answer

It's a matter of style and preference, but a few people have published Angular.js style guides and the first code example you posted seems to align with the generally accepted practice.

Bindable Members Up Top | Angular Style Guide

Here are three style guides that seem to be quite popular, that agree on many things and differ on some:

Igor Yamshchykov
Igor Yamshchykov
24,397 Points

Thank you for quick answer! I'll go through this style guides.