AngularJS修改被抄除的内容

时间:2014-02-26 14:09:30

标签: javascript angularjs

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

基本上是这样的指令:

<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}}中基本上是字符串的所有内容都会被包含在<code ng-transclude></code>元素中时放入span

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

我需要将此{{codeValue}}传递给语法突出显示功能,该功能将返回语法突出显示的代码,该代码将是原始HTML(因此原始字符串(已清理和转义)将转换为带有span标记的HTML)。然后,需要将此原始HTML放在code元素内。

我尝试过使用transclude功能,但内容似乎已被转录。

2 个答案:

答案 0 :(得分:2)

所以基本上你想将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

    }
};

答案 1 :(得分:2)

这就是我最终做的事情:

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