javascript - AngularJS 修改嵌入的内容

标签 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 内元素。

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

最佳答案

这就是我最终所做的:

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

关于javascript - AngularJS 修改嵌入的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22043894/

相关文章:

从文本中删除 bb_quotes ([quote..] [/quote]) 的 Javascript

html - 如何规范化嵌套在表格中的 bs-datepicker 的样式

javascript - 更新指令的两个实例的范围值

javascript - 将下划线与 jshint 一起使用

angularjs - 在 promise 链的末尾捕捉错误

angularjs - 将日期格式设置为年份

javascript - 变量变量在 angularjs 中可能吗?

javascript - 使用 Javascript 转义空白字符

javascript - AngularJS 模块架构

Javascript 加载图标无法在浏览器上禁用 JS 的情况下使用