如何获取自定义指令的内部html?

时间:2014-05-24 06:44:43

标签: angularjs

我想为这个

创建一个html指令
<div my-modal my-modal-id="test">
    <div class="inner">Hello Inner</div>
</div>

想要从上面生成html到像

这样的东西
<div id="test">
    <h1>My Heading</h1>
    <div class="b">
        Hello Inner
    </div>
</div>

JS

.directive('myModal', function() {
    return {
        restrict: 'A',
        replace: true,
        scope: {
            myModalId: '@'            
        },
        compile: function(tEle, tAttrs, transcludeFn) {
            //what to do here?
            //I want to get div.inner of the original html
        },
        template: '<div id="{{myModalId}}">' +
            '<h1>My Heading</h1>' +
            '<div class="b"></div>' +
            '</div>'
    }
});

1 个答案:

答案 0 :(得分:1)

我不知道您是否可以使用模板,它似乎会在调用compile之前覆盖现有的html。抓取HTML并自行替换它似乎有效(plnkr):

.directive('content', function($compile) {
  var dir = {
    restrict: 'E',
    xemplate: '<div id="{{myModalId}}">' +
      '<h1>My Heading</h1>' +
      '<div class="b">Original:<br/><pre>{{original}}</pre></div>' +
      '</div>',
    compile: function(element, attrs, linker) {
      var original = element.html(); // grab original
      element.html(dir.xemplate); // set template html manually
      return function(scope, element, attributes) {
        scope.original = original
      }
    }
  };
  return dir;
});