使用指令将HTML传递给TemplateURL

时间:2017-10-28 20:59:55

标签: angularjs angularjs-directive

我正在尝试将指令标记内的HTML放入模板文件中并在屏幕上呈现

HTML

<insert-test-tab><b>Put this text in the template test.html</b></insert-test-tab>

的script.js

directive('insertTestTab', function() {
  return {
    replace: true,
    link: function (scope, element, attr) {

    },
    templateUrl: function (elem, attr) {
      return 'test.html'
    },
  }
}

的test.html

<div>
  <p>bla bla bla</p>
  <p>[[I want to get that HTML inside <insert-test-tab> here]]</p>
</div>

期望的输出

<div>
  <p>bla bla bla</p>
  <b>Put this text in the template test.html</b>
</div>

谢谢。

2 个答案:

答案 0 :(得分:1)

指令定义:

  directive('insertTestTab', function() {   
    return {
   replace: true,
   transclude: true,
   link: function (scope, element, attr) {

    }, templateUrl: function (elem, attr) {
      return 'test.html'
    },   
 } 
}

的test.html:

<div>
  <p>bla bla bla</p>
  <p><ng-transclude></ng-transclude></p>
</div>

答案 1 :(得分:0)

您可以使用指令转换功能实现此目的。

所以你的指令定义应该如下:

directive('insertTestTab', function() {   return {
    replace: true,
    transclude: true,
    link: function (scope, element, attr) {

        }, templateUrl: function (elem, attr) {
          return 'test.html'
        },   
    } 
}

test.html应该::

<div>
  <p>bla bla bla</p>
  <p><ng-transclude></ng-transclude></p>
</div>

希望这对您有用(Ref :: https://codepen.io/pankajbadukale/pen/aVbGaM