Project Development

Project Reflection: How I Organized My AngularJS/Ionic Application

In an effort to better present and document my code, I decided to go through what I’ve written thus far with a fine-tooth comb. Fortunately, AngularJS (and consequently Ionic) is an MVC-based framework, meaning that code is logically divided between the model (the data and inner workings of the program), the view (what the user sees), and the controller (which controls the view based on the model).

For example, let's say the model is an array of 10 numbers, which exists somewhere in the code. The user may only see numbers one and two. The controller controls what the user sees, setting the array to only display numbers one and two.  For more examples, read this excellent post by Muhammad Azamuddin.   

So, merely by being an AngularJS app, Leder was already organized in some respect. I had a folder for HTML pages, a folder for external libraries, and a JavaScript folder for all my JavaScript files. In that folder, I had three JavaScript files called controllers, services, and app. When my controllers file surpassed 300 lines, I decided to reorganize.

I considered moving from a class-type organizational structure to one organized by features. John Papa makes a good case why the feature structure is superior, but I find the class-type organization to be more intuitive. Features change and develop, but the basic business and app logic stays the same.

I followed the structural guidelines outlined by Josh MoroneyBasically, I added a separate folder for services, controllers, and factories within my larger JavaScript folder. I moved code that better fits in a factory to a separate factories.js file. The libraries folder for external libraries and templates folder for my HTML files remained the same.

                                                                                Old structure vs. new structure.

The top of each controller file has a module.

angular.module('leder.outlineController', [])
.controller('OutlineCtrl', function($scope, $stateParams) {
    ...
}

And all modules are injected as dependencies in the app.js file.

angular.module('leder', ['ionic', 'leder.controllers', 'leder.editSourceController', 'leder.projectController', 'leder.projectPageController', 'leder.sourcesController', 'leder.outlineController', 'leder.services', 'leder.evernoteService', 'ionic.utils'])

.run(function($ionicPlatform) {
    ...
}

Going through all my files was a bit tedious, but the result is much cleaner, clearer code. I also got over my fear of cutting and moving code around. In the end, the functionality is exactly the same as in the original version, but I now have a much easier time reading and parsing my files. 

How do you organize your code? What tips do you have to make my file system better? Leave your thoughts in the comments.