Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.