0

So I have a directive that can either be an attribute, or an element. When it's an attribute, I don't want to load any template inside the existing element it's been declared on. When it's an element, I want to load a given template and populate the directive's custom tag.

I've tried:

return {
  link: function(){...},
  templateUrl: function(element, attrs){
    url = "path/to/directive/template.html";

    // Checking if directive is used as an attribute here
    if(angular.isDefined(attrs.myDirective)){
       url = null; // Tried false, empty string, etc. but angular not happy with any of it
    }
    return url;
  }
}

Any idea how to achieve this?

gkpo
  • 2,623
  • 2
  • 28
  • 47

1 Answers1

0

Have you considered writing 2 directives with the same name, and using restrict to specify the different template behaviour?

function directiveFactory(usesTemplate){

    return ['$timeout', function($timeout){
        var ddo = {
            link: function(scope, el,attr){
                $timeout(someThing, 1000) 
                //if you dont actually need to use a timeout, might 
                //i suggest scope.$applyAsync if your version of angular supports it?
            }
        }

        if(usesTemplate){
            ddo.restrict = 'E';
            ddo.templateUrl = 'path/to/template';
        } else {
            ddo.restrict = 'A';
        }

        return ddo;
    }];

}

module('somename').directive('someName', directiveFactory(true)).directive('someName', directiveFactory(false));
Iain
  • 2,259
  • 1
  • 16
  • 18
  • don't think you can use same name for 2 directives. – charlietfl Jun 08 '16 at 23:56
  • @charlietfl: You can. Its great for attaching new behaviour to existing directives. (logging every ng-click activation for example) – Iain Jun 09 '16 at 00:03
  • Thanks for your reply, the problem is that i'm using angular providers inside the link function. And these providers are declared in the .directive() function. `.directive('myDirective', ['$timeout', function($timeout){}])`. And if the link function is outside, it will throw an error since providers are undefined. – gkpo Jun 09 '16 at 12:34
  • @MonsieurNinja try it now – Iain Jun 10 '16 at 01:54