creating a new directive with angularjs

First a clarification..

  • I do not recommend overusing $compile, there are better ways for binding event listeners to a scope.
  • I solved this question for me to learn how compilation works and to share it with others.

what happens when manipulating template element inside a the compile function?

  • The compilation phase iterates down the DOM , from parent to children element.
  • When you manipulate children of a DOM element inside a compile function it happens before $compile got down to these children elements to collect their directives, so every change you make to the contents of the template element will be compiled and linked with the continuation of the compilation phase.
  • This is not the case when you manipulate the template element itself , then $compile will not look for more directives in that same element because it’s only collecting directives once per each DOM element.
  • So these attributes you added are just not being compiled!

Lets $compile it manually:

  • I tried to add $compile(el) but my browser crashed (don’t laugh at me), The reason is it got into a loop where it’s infinitely compiling itself.
  • So I removed the directive attribute and then $compile again.
  • I set { priority:1001 } and { terminal:true }. This iss needed to prevent other directive compile functions to run before our directive or after out manual compiling.

Solution:

here is a plunker: http://plnkr.co/edit/x1ZeigwhQ1RAb32A4F7Q?p=preview

app.directive('hover', function($compile){
  return{
    restrict: 'A',
    controller: function($scope) {

       // all the code
    },

    priority: 1001, // we are the first

    terminal: true, // no one comes after us

    compile: function(el, attrs){

      el.removeAttr('hover'); // must remove to prevent infinite compile loop :()

      el.attr('data-ng-mouseover', 'onHover('+attrs.index+')');
      el.attr('data-ng-mouseleave', 'mouseLeave()');
      el.attr('data-ng-click', 'onClick('+attrs.index+')');
      el.attr('data-ng-class', '{'+ attrs.onhover +': hover == ' + attrs.index + ' || selected == ' + attrs.index + '}');

      var fn =  $compile(el); // compiling again

      return function(scope){
        fn(scope); //
      }
    }
  }
});

Leave a Comment