Angular 指令不同的模板 [英] Angular Directive Different Template

查看:25
本文介绍了Angular 指令不同的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量类型的指令 myDirective.如果我运行 <my-directive type="X"> 我希望指令使用 templateUrl: x-template.html.如果我执行 <my-directive type="Y"> 我希望指令使用 templateUrl: y-template.html.

I have a directive myDirective with variable type. If I run <my-directive type="X"> I want the directive to use templateUrl: x-template.html. If I do <my-directive type="Y"> I want the directive to use templateUrl: y-template.html.

这是我当前的指令.

app.directive('myDirective', function() {
    var myDirective = {
        templateUrl: 'X-template.html',
        restrict: 'E',
        scope: {
            type: '=' 
        },
    };
    return myDirective;
});

我通读了 stackoverflow 和 angular 文档,但没有找到我需要的任何内容.

I read thru stackoverflow and angular documentation but have not found anything that I need.

我现在正在尝试做一些事情:

I am now trying to do something along the lines of:

if ($scope.type === 'X') {
    templateUrl: 'X-template.html',
}
else if ($scope.type === 'Y') {
    templateUrl: 'Y-template.html',
}

但是不知道在哪里做.

你们知道这是否可能以及如何实现吗?

Do you guys know if this is possible and how?

推荐答案

你可以解决 这个问题compile中使用ng-include:

You can work around this issue using ng-include inside compile:

app.directive('myDirective', function() {
    return {
        restrict: 'E',
        compile: function(element, attrs) {
            element.append('<div ng-include="\'' + attrs.type + '-template.html\'"></div>');
        }
    }
});

小提琴

这篇关于Angular 指令不同的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆