AngularJS指令动态模板

时间:2014-04-14 16:21:58

标签: angularjs angularjs-directive angularjs-scope

我试图根据范围值使用不同的模板制作指令。

这是我到目前为止所做的,我不知道为什么不起作用http://jsbin.com/mibeyotu/1/edit

HTML元素:

<data-type content-attr="test1"></data-type>

指令:

var app = angular.module('myApp', []);

app.directive('dataType', function ($compile) {

    var testTemplate1 = '<h1>Test1</h1>';
    var testTemplate2 = '<h1>Test2</h1>';
    var testTemplate3 = '<h1>Test3</h1>';

    var getTemplate = function(contentType){

        var template = '';

        switch(contentType){
            case 'test1':
                template = testTemplate1;
                break;
            case 'test2':
                template = testTemplate2;
                break;
            case 'test3':
                template = testTemplate3;
                break;
        }

        return template;
    }; 

    var linker = function(scope, element, attrs){
        element.html(getTemplate(scope.content)).show();
        $compile(element.contents())(scope);
    };

    return {
        restrict: "E",
        replace: true,
        link: linker,
        scope: {
            content:'='
        }
    };
});

4 个答案:

答案 0 :(得分:112)

您可以将指令定义对象的template属性设置为将返回动态模板的函数:

restrict: "E",
replace: true,
template: function(tElement, tAttrs) {
    return getTemplate(tAttrs.content);
}

请注意,此时您无法访问范围,但您可以通过tAttrs访问这些属性。

现在您的模板正在编译阶段之前确定,您不需要手动编译它。

答案 1 :(得分:20)

你也可以这么简单地做到这一点:

appDirectives.directive('contextualMenu', function($state) {
    return {
      restrict: 'E',
      replace: true,
      templateUrl: function(){
        var tpl = $state.current.name;
        return '/app/templates/contextual-menu/'+tpl+'.html';
      }
    };
});

答案 2 :(得分:15)

1)您在html中传递内容作为属性。试试这个:

element.html(getTemplate(attrs.content)).show();

而不是:

element.html(getTemplate(scope.content)).show();

2)指令的数据部分正在编译,所以你应该使用别的东西。而不是数据类型,例如数据N型。

这是链接:

http://jsbin.com/mibeyotu/6/edit

答案 3 :(得分:10)

如果您需要根据$scope变量加载模板,可以使用ng-include执行此操作:

.directive('profile', function() {
  return {
    template: '<ng-include src="getTemplateUrl()"/>',
    scope: {
      user: '=data'
    },
    restrict: 'E',
    controller: function($scope) {
      //function used on the ng-include to resolve the template
      $scope.getTemplateUrl = function() {
        //basic handling
        if ($scope.user.type == 'twitter') {
          return 'twitter.tpl.html';
        }
        if ($scope.user.type == 'facebook') {
          return 'facebook.tpl.html';
        }
      }
    }
  };
});

参考:https://coderwall.com/p/onjxng/angular-directives-using-a-dynamic-template