如何通过指令编辑元素的html

How to edit html of an element through a directive

本文关键字:html 元素 编辑 何通过 指令      更新时间:2023-09-26

在AngularJS中,我如何访问指令属性所在元素的实际html ?我对编辑它的属性不感兴趣,我想实际操作html本身。将元素更改为span,甚至更改为注释。

例如:

<div my-directive>
    <h1>hey</h1>
</div>

我想改成:

<span my-directive>
    <h1>hey</h1>
</span>

或甚至到:

<!-- div my-directive -->
    <h1>hey</h1>
<!--/div -->

你可以试试这个:http://jsfiddle.net/YWfSF/3/

.directive('myDirective', function() {
  return {
    compile: function(elem) {
        elem.replaceWith('<span>' + elem.html() + '</span>');
    }
  }
});

这里有一个非常简单的例子。根据你的需要,你可以稍微扩展一下。

app.directive('mydirective', function() {
  return {
    restrict:'A',
    template: '<span my-directive><h1>hey</h1></span>',
    replace:false,
    compile: function compile(tElement, tAttrs, transclude){
      console.log('tElement',tElement);
      console.log('tAttrs',tAttrs);
      console.log('transclude',transclude);
    }
  }
});
我知道,这是广义的,但你的问题也是;)玩得开心!

编辑:忘记了plunkr link