Search code examples
javascriptangularjsangularjs-directiveencapsulation

How to Wrap a JS Encapsulating Function Around a Directive


I have seen this done before, I am trying to implement an encapsulating function, but it breaks my directive. Without the encapsulation it works. Has anyone done this before or does anyone know why it breaks the directive?

https://jsfiddle.net/ciderman/a0n9h0ar/1/

(function () {
  myApp.directive('myPerfectDirective', function(){
    return{
      restrict: 'E',
      scope: {
        data: '='
      },
      template: '<p>my perrrrrrfeccct directivve</p>',
      templateUrl: 'book-widget.html'
    }
  });
});

Solution

  • What you're talking about is called an IIFE (Immediately-invoked function expression).

    You've got part of it right, the problem as Alejandro has pointed out you're missing the () which will invoke the function.

    So change your code to look like this:

    (function () {
      myApp.directive('myPerfectDirective', function(){
        return{
          restrict: 'E',
          scope: {
            data: '='
          },
          template: '<p>my perrrrrrfeccct directivve</p>',
          templateUrl: 'book-widget.html'
        }
      });
    })();
    

    For more information on IIFE(pronounced IIFY) look here What is the (function() { } )() construct in JavaScript?