Angular指令可选templateUrl

时间:2016-06-08 23:49:08

标签: javascript angularjs directive

所以我有一个可以是属性或元素的指令。 当它是一个属性时,我不想在声明它的现有元素中加载任何模板。 当它是一个元素时,我想加载一个给定的模板并填充该指令的自定义标记。

我试过了:

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;
  }
}

知道如何实现这个目标吗?

1 个答案:

答案 0 :(得分:0)

您是否考虑过使用相同名称编写2个指令,并使用restrict指定不同的模板行为?

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));