繁体   English   中英

AngularJS修改被包含的内容

[英]AngularJS modifying the transcluded content

我正在尝试构建语法突出显示指令。

基本上像这样的指令:

<div syntax-highlight="language">{{codeValue}}</div>

应该变成:

<div syntax-highlight="language">
    <pre><code>{{codeValue that has been syntax highlighted with span tags}}</code></pre>
</div>

所以我有:

return {
    scope: {
        'syntaxHighlight': '@'
    },
    template: '<pre><code ng-transclude></code></pre>',
    transclude: true,
    link: function (scope, element, attributes, controller, transclude) {

    }
};

当前运行此代码时, {{codeValue}}内部的所有内容(基本上是一个字符串)都被包裹在span元素中,然后放入<code ng-transclude></code>中。

这不是很好,因为我不只是想要在code元素内输入字符串。 我需要先修改此值,然后才能将其排除。

我需要将此{{codeValue}}传递到语法突出显示函数中,该函数将返回语法突出显示的代码,该代码将是原始HTML(因此,原始字符串(经过清理和转义的原始字符串)将变成带有span标签的HTML)。 然后需要将此原始HTML放入code元素中。

我试过使用transclude函数,但似乎内容已被包含在内。

所以,基本上,您想将CodeValue传递给指令并在链接函数中对其进行操作?

关于什么:

<syntaxhighlight codevalue="codeValue"> </syntaxhighlight>

    return {
     restrict: 'E',
     scope: {'codevalue': '='},
     template: '<div> <pre><code ><span>{{sanitizedText}}</span></code></pre></div> ',
     replace: true,
     link: function (scope, element, attributes, controller) {

       scope.sanitizedText = textEditingFunction(scope.codevalue); //pass codevalue to the modifying function, who will return the sanitized text

    }
};

这就是我最终要做的事情:

['$sce', function($sce){

    return {
        scope: {
            'syntaxLanguage': '@'
        }, 
        restrict: 'AE',
        template: codeBlockTemplate, 
        transclude: true, 
        replace: true, 
        link: function (scope, element, attributes, controller, transclude) {

            //transclude's clone is children elements of the directive element, it will wrap any unwrapped text nodes with the span tag
            transclude(scope, function (clone) {

                //get the directive element's content as text, this will be the {{code}}
                var code = angular.element(clone).text();

                //convert the code string into a highlighted code string
                var highlightedCode = hljs.highlight(scope.syntaxLanguage, code, true);

                //bind to the scope as trusted HTML
                scope.highlightedCode = $sce.trustAsHtml(highlightedCode.value);

            });

        }
    };

}]

以此为模板:

<pre><code ng-bind-html="highlightedCode"></code></pre>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM