1

I have started learning AngularJS and while going through some code samples I came across the following:

(function(app) { 
    'use strict';
    app.directive('sideBar', sideBar);
    function sideBar() { 
      return { 
         restrict: 'E', 
         replace: true, 
         templateUrl: '/scripts/spa/layout/mypage.html' 
         } 
     }
  })(angular.module('common.ui'));

The above code creates a custom directive using IIFE. I am very confused about the last line of the code. It is passing a module named common.ui. Can someone explain me how this way of passing a parameter works and how this can be rewritten in a different way?

peteb
  • 18,552
  • 9
  • 50
  • 62
Massey
  • 1,099
  • 3
  • 24
  • 50
  • `angular.module('common.ui')` becomes referenced by `app`. See http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript. – Jasen Jun 21 '16 at 17:57

3 Answers3

1

angular.module('common.ui') becomes referenced by app. See What is the (function() { } )() construct in JavaScript?.

You can declare it normally

(function() {
    var app = angular.module('common.ui');
})();
Community
  • 1
  • 1
Jasen
  • 14,030
  • 3
  • 51
  • 68
0

Without the final parens (passing the angular.module) it would just be a function that was defined but didn't do anything and it wouldn't be callable without a name. The parens are invoking it immediately.

As far as rewriting it could be defined with a name and then called. Because it would be called only once there is no need to give it a name. Instead it is just run.

There are other reasons to use IIFE (like closures for encapsulating data or getting around async code) but in this case it is really just avoiding naming and then calling.

Mike Cheel
  • 12,626
  • 10
  • 72
  • 101
0

the upper function isn't in the scope or being seen untile this () exist which you are defining parameter to the upper function and call it .

abdoutelb
  • 1,015
  • 1
  • 15
  • 33