Massey
Massey

Reputation: 1125

AngularJS and IIFE

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?

Upvotes: 1

Views: 305

Answers (3)

Jasen
Jasen

Reputation: 14250

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');
})();

Upvotes: 1

abdoutelb
abdoutelb

Reputation: 1053

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 .

Upvotes: 0

Mike Cheel
Mike Cheel

Reputation: 13106

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.

Upvotes: 0

Related Questions