user3917453 user3917453 - 1 year ago 85
Javascript Question

Code organization AngularJS huge controller

I have a huge controller, I have split it into subcontrollers, which I put into other files according to their functionality.

Everything works fine, but I need an advice and the answer on my question:
have I done it right?

here is a huge controller:

function controller($scope, $http) {
someFunction($scope, boolA, function1, function2);

here is the code of my subcontroller in other file, which I load after the front controller:

function someFunction($scope, boolA, function1, function2) {
//code where I use all the parametrs of function
function someFunctionSubcontoller() {
//here is used another function from other subcontroller

Is it ok to send functions as parametrs? Is it okay whether I don't return anything from subcontrollers, because $scope watches everything? Is it okay whether I use some functions of contoller in another one?

Now I see that's not good and not right, but I need to split main contoller because there are more than 10k rows of code in it.

thanks for your advice and help !!!

Answer Source

A Controller with 10,000 lines of code screams that you are breaking the Single Responsibility Principle multiple times in your code.

Instead of making "sub-controllers", you should consider first refactoring your code and moving reusable code segments into Services. Then, look for common components in your UI which you can convert to Directives, and move some logic into a Controller for those Directives, using isolate scopes. You will find that it's much easier to control and test these elements when they are responsible for themselves.

Next, look into using the 'Controller As' Syntax, which allows you to break your ties with $scope. Using $scope is an anti-pattern, since it is very difficult to identify where items placed directly on $scope originate from, are used, and are modified. It is very easy to find that an object has a value other than what you intended because it was modified somewhere else. From the Angular Documentation:

•Using controller as makes it obvious which controller you are accessing in the template when multiple controllers apply to an element.

•If you are writing your controllers as classes you have easier access to the properties and methods, which will appear on the scope, from inside the controller code.

•Since there is always a . in the bindings, you don't have to worry about prototypal inheritance masking primitives.

Bottom line, you will probably find that if you refactor your code instead of just "breaking it up", you will end up with a much more manageable, testable, and reliable solution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download