Set templateUrl base on attribute in directive

▼魔方 西西 提交于 2019-12-13 11:52:50

问题


I'm working on a set of angular directives and I want to load the correct template based on the presence or value of an attribute.

<my-form horizontal> </my-form>
<my-form vertical> </my-form>

If horizontal, templateUrl should be /partials/horizontal-form and If vertical, templateUrl should be /partials/vertical-form

I'm interested in the templateUrl because I can't use template since the html depends on the attributes. In the compile.pre function, the html has already been loaded.

If there is another way of achieving this, I'm open to it since I'm now starting with angular and the more info the better.

Thanks


回答1:


One of the solutions for this is to use an ng-include inside the template file.

The first attribute inside of the template file will have something like :

<div ng-include = "getTemplate()">

</div>

In your directive code you would write something like :

scope : {direction : "="},
link : function(scope,element,attrs)
{
    scope.getTemplate = function(){
        if(scope.direction === "horizontal")
        {
            return "horizontal.html";
        }
        return "vertical.html";
    }
}

Hope this helps!




回答2:


fyi this is now properly fixed in angular 1.1.4

you can pass a function to templateUrl. input parameters are element, attributes. and returns a string (the templateUrl you wish to use)

docs here: http://code.angularjs.org/1.1.4/docs/guide/directive



来源:https://stackoverflow.com/questions/12444872/set-templateurl-base-on-attribute-in-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!