AngularJS指令用于解析和替换自定义元素内容

Gre*_*reg 10 angularjs angularjs-directive

我想创建一个简单的markdown指令,接受元素中的一些内容,解析它并用html替换它.

所以这:

<markdown>#Heading</markdown>
Run Code Online (Sandbox Code Playgroud)

或者这个(其中$ scope.heading ='#Heading';)

<markdown>{{heading}}</markdown>
Run Code Online (Sandbox Code Playgroud)

变成这样:

<h1>Heading</h1>
Run Code Online (Sandbox Code Playgroud)

我的指令到目前为止(显然不完整!):

.directive('markdown', function () {
    return {
        restrict: 'E',
        replace: true,
        link: function ($scope, $element, $attrs) {
            // Grab contents
                var contents = /* How do I do this? */

                var newContents = Markdowner.transform(contents);

                // Replace <markdown> element with newContents
                /* How do I do this? */
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

我不确定如何获取指令的内容?我需要编译吗?!

解析Markdown只是一个例子

jes*_*vin 7

干得好!

工作演示

app.directive('markdown', function() {
  return {
    restrict: 'E',
    transclude: true,
    compile: function(elem) {
      elem.replaceWith(Markdowner.transform(elem.html()));
    }
  }
});
Run Code Online (Sandbox Code Playgroud)


Ser*_*hiv 6

ngTransclude是专门为此而设计的.

myModule.directive('heading', function() {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: true,
        template: '<h1 ng-transclude></h1>'
    };
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

<heading><span>{{foo}}</span></heading>
Run Code Online (Sandbox Code Playgroud)

这是一个工作小提琴(角度1.2.7).

另外,我猜你需要某种降价整合.这是一个使用transclude的版本,以便您最终得到一个div容器.

这个跳过整个转换行为,我猜它更接近你所追求的.