Подтвердить что ты не робот

Угловые шаблоны Directular

Я пытаюсь сделать директиву с разными шаблонами на основе значения области.

Это то, что я сделал до сих пор, и я не знаю, почему не работает 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:'='
        }
    };
});
4b9b3361

Ответ 1

1) Вы передаете контент как атрибут в свой html. Попробуйте следующее:

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

вместо:

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

2) часть данных директивы собирается, поэтому вы должны использовать что-то еще. Вместо типа данных, например. Датан типа.

Вот ссылка:

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

Ответ 2

Вы можете установить свойство template объекта определения директивы для функции, которая вернет ваш динамический шаблон:

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

Обратите внимание, что на данный момент у вас нет доступа к области, но вы можете получить доступ к атрибутам через tAttrs.

Теперь ваш шаблон определяется до этапа компиляции, и вам не нужно вручную его компилировать.

Ответ 3

Вы также можете сделать это очень просто:

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

Ответ 4

Если вам нужно загрузить шаблон на основе переменных $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