Angular module setup

I like the Angular module setup and syntax that John Papa and Todd Motto have been suggesting recently. The key component of which is the wrapping of each module declaration in an IIFE, which helps to keep the global scope nice and clean, but also the declaring of controller functions, etc. outside the actual .controller method, eg.

(function(){
    
    angular
       .module('app', [])
       .controller('SomeCtrl', ['$scope', SomeCtrl]);

    function SomeCtrl ($scope) {
 
    }

})();


What's nice about this? Well, it seems to me much easier to read at a glance than having the function declared within the controller declaration as is commonly seen, eg.

    
    angular
       .module('app', [])
       .controller('SomeCtrl', ['$scope', function ($scope) {
            
           //lots of interesting and exiting stuff 
       

       }]); //somewhere way down the page your controller declaration is closed off


Not so obvious a difference on this simple example, but does make a difference to readability I think with more complex controller functions.

With the IIFE I am using grunt-wrap to add this to all the module .js files as part of the build process, with the following simple config:

wrap: {
        basic: {
            src: [ '<%= app_files.js %>' ],
            dest: '<%= build_dir %>/',
            options: {
                wrapper: ['(function () {\n \'use strict\';\n', '\n})();']
            }
        }
    }

Comments