【问题标题】:AngularJS modifying the transcluded contentAngularJS 修改嵌入的内容
【发布时间】:2014-03-29 10:17:47
【问题描述】:

我正在尝试构建一个语法高亮指令。

基本上是这样的指令:

<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}}(基本上是一个字符串)中的所有内容都会被放入&lt;code ng-transclude&gt;&lt;/code&gt;,同时被包装在span 元素中。

这不好,因为我不只是想要code 元素内的字符串。我需要在被嵌入之前修改这个值。

我需要将此{{codeValue}} 传递给语法高亮函数,该函数将返回语法高亮代码,该代码将是原始 HTML(因此原始字符串(经过净化和转义)会变成带有 span 标签的 HTML)。然后需要将这个原始 HTML 放入 code 元素中。

我尝试过使用 transclude 功能,但内容似乎已经被嵌入了。

【问题讨论】:

  • 我假设您在链接函数中调用语法高亮函数?你不能只附加到其中的元素吗?

标签: javascript angularjs


【解决方案1】:

这就是我最终做的:

['$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>

【讨论】:

    【解决方案2】:

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

    怎么样:

    &lt;syntaxhighlight codevalue="codeValue"&gt; &lt;/syntaxhighlight&gt;

        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
    
        }
    };
    

    【讨论】:

    • transclude: true 的意义何在?你最终没有使用任何嵌入工具。我确实做了一些非常相似的事情。此外,它与我的用例不匹配,因为代码值将在 &lt;syntaxHighlight&gt; 元素内。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多