Sunday, November 26, 2017

Javascript closures - Angular approach

One big monolithic app 


Let's create a module in angular

// Below code is a setter which instantiate an angular module
angular.module('app',                           ['ui.router','toaster','ngAnimate','chart.js']);


The above approach is used best when you are creating a monolithic angular application where your application consists only a one big module and all the controllers, configurations, the routes, directives, factories, and the services are linked together.

but if you wish to create an angular app where there's separation of concerns. You'll definitely have to breakdown your application into reusable modules.

The modular way of doing things

(function () {                                          
       'use strict'; 
       angular.module('app', [
                     'ui.router','toaster','ngAnimate', 'chart.js'
           ])
})();

but wait. when you do it like this your app can't be accessed from the global scope. Then you'll have to turn the whole app into a collection of modules.

(function () { 
       'use strict';
        var app = angular.module('justforfunApp', ["ui.router","toaster","ngAnimate","chart.js" ]) 
})() 
//Below code won't execute since the app can't be accessible from the global scope
app.run(function ($window) {
        // some operations here
})


But why ?

If you declare the app variable as a  global then your variable maybe conflict with other javascript variable with the similar name. So if you are making the application as reusable components. Probably your components should't be conflicting with the rest of the code. That's why we use this kinda approach

There are few good examples here

The better way

To show how its done, I've created a sample angular application. The modules are categorized based on the features/functionality (customer, administrator) rather than the type (models, views and controllers)

I followed the LIFT principle

L - Locating your code
I - Identifying the code at a glance
F - Flat file structure
T - Try to stay dry (Don't repeat yourself)


Finally, there are no rules

There are no hard and fast rules of coding. The best way is the way you feel more comfortable.