AngularJS - 带动态模板的指令

时间:2015-07-20 09:02:01

标签: javascript angularjs templates dynamic directive

我想知道 - 如何使用动态模板制作Directive。 问题是 - 当我在主页上以及主要类别(例如page1page2时,我的模板应该包含所有divs

当我在subpage1subpage2这样的子菜单上时,我想只有3 divs。 如何动态实现呢?我知道我必须在每个子页面上使用我的指令

<my-template whereIam="page1"></my-template><my-template whereIam="subpage2"></my-template>

但我无法实现它。你能帮帮我吗?

我的指令与示例模板:

angular.module('dynamic-template').directive('myTemplate', function () {
    return {
        restrict: 'E',
        template: "<div1> "
                    + "<h1> Main pages and subpages </h1>"
                + "</div1>"
                + "<div2>"
                    + "<h2> Main pages and subpages </h2>"
                + "</div2>"
                + "<div3>"
                    + "<h3> Main pages and subpages </h3>"
                + "</div3>"
                + "<div4>"
                    + "<h4> Only mainpages </h4>"
                + "</div4>"
                + "<div5>"
                    + "<h5> Only subpages </h5>"
                + "</div5>"                     
    };
}]);

其中一个页面上的HTML:

<my-template whereIam="??" ></menu-template>

示例Plunkr

http://plnkr.co/edit/kVk3mJWUbTqhFEHVUjt1?p=preview

我已经搜索过这个,但我输了:(

我是否使用$ compile来实现它?

2 个答案:

答案 0 :(得分:1)

*注意:我个人更喜欢将模板放在一个单独的文件中(使用templateUrl)

但是......

您可以浏览页面类型的页面并使用ng-if's。

angular.module('dynamic-template').directive('myTemplate', function () {
return {
    restrict: 'E',
    scope: { isMain: "=main"},
    template: "<div1> "
                + "<h1> Main pages and subpages </h1>"
            + "</div1>"
            + "<div2>"
                + "<h2> Main pages and subpages </h2>"
            + "</div2>"
            + "<div3>"
                + "<h3> Main pages and subpages </h3>"
            + "</div3>"
            + "<span ng-if='isMainPage'><div4>"
                + "<h4> Only mainpages </h4>"
            + "</div4>"
            + "<div5>"
                + "<h5> Only mainpages </h5>"
            + "</div5></span>"                     
};
}]);

并在您的html中(当它是主页时)

<my-template main="true"/>

否则,我对类似问题的回答可能适合您:

这种方式确实需要您为每个文件创建单独的html文件

See other Stackoverflow answer

或直接使用Plunkr

Plunkr

app.directive('myDirective', [function(){

return {
    template: '<div ng-include="getTemplate()"></div>',
    restrict: 'E',
scope: {template: '='},
link: function(scope, element, attr, ctrl) {
  var baseURL = 'templates/myDirective.'

  scope.getTemplate = function(){
      baseURL = "" //remove this
      return baseURL + scope.template + ".html"
    };
}
};
}]);

答案 1 :(得分:1)

为什么不像rmuller所说的那样使用templateURL,但你可以传入param并返回正确的模板示例

templateUrl: function (elem, attrs) {
                if (attrs.isMain === 'mainPage') {
                    return 'main_view.html';
                }
                return 'other_view.html';
            },

因此,您可以将模板分成文件。我认为这是我个人认为最好的方式