TonyTakeshi
TonyTakeshi

Reputation: 5929

AngularJS - Override directive's compile function doesn't invoke link function?

I customise directive template by overriding directive's compile, however it won't invoke link function after it run compile function.

angular.module('app').directive('ngValidate', ['$compile', function($compile){
  return {
    restrict: 'A',
    require: '?ngModel',
    compile:function($element, $attrs, linker){
        // this run
        console.log('compile>>>');

        // append error message
        $element.append('<div></div>');
        $element.bind('blur',function(){
            console.log('onblur');
        });

        $compile($element.contents());
    },
    controller: function($scope, $element, $attrs){
        // this run
        console.log('controller>>>');
    },
    link: function($scope, $element, $attrs, ctrl) {
        // this doesn't run
        console.log('link>>>');
    }
  }
}]);

Reason I need to run link after compile is I would like to access the scope, possible to access scope from compile?

Upvotes: 1

Views: 2011

Answers (1)

shaunhusain
shaunhusain

Reputation: 19748

As is stated in the comment, if you have a compile function it should return the link function instead of having it separately defined on the directive definition object.

angular.module('app', []).directive('ngValidate', ['$compile', function($compile){
  return {
    restrict: 'E',
    require: '?ngModel',
    compile:function($element, $attrs, linker){
        // this run
        console.log('compile>>>');

        // append error message
        $element.append('<div></div>');
        $element.bind('blur',function(){
            console.log('onblur');
        });

        $compile($element.contents());
        return function($scope, $element, $attrs, ctrl) {
          // this doesn't run
          console.log('link>>>');
        }
    },
    controller: function($scope, $element, $attrs){
        // this run
        console.log('controller>>>');
    }
  }
}]);

http://jsfiddle.net/uGk4f/

Upvotes: 2

Related Questions