首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AngularJS修改遮挡内容

AngularJS修改遮挡内容
EN

Stack Overflow用户
提问于 2014-02-26 14:09:30
回答 2查看 1.3K关注 0票数 2

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

基本上是这样的指令:

代码语言:javascript
复制
<div syntax-highlight="language">{{codeValue}}</div>

应转化为:

代码语言:javascript
复制
<div syntax-highlight="language">
    <pre><code>{{codeValue that has been syntax highlighted with span tags}}</code></pre>
</div>

所以我要说的是

代码语言:javascript
复制
return {
    scope: {
        'syntaxHighlight': '@'
    },
    template: '<pre><code ng-transclude></code></pre>',
    transclude: true,
    link: function (scope, element, attributes, controller, transclude) {

    }
};

当该代码当前运行时,{{codeValue}}中的所有内容(基本上是一个字符串)在包装到span元素中时都会被放入span中。

这不太好,因为我不只是希望在code元素中有一个字符串。在被排除之前,我需要修改这个值。

我需要将这个{{codeValue}}传递到语法突出显示函数中,该函数将返回语法突出显示的代码,该代码将是原始的HTML (因此一个原始字符串(净化和转义)将被转换为带有span标记的HTML )。然后,这个原始的HTML需要放在code元素中。

我试过使用transclude函数,但内容似乎已经被屏蔽了。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-26 15:24:23

这就是我最后所做的:

代码语言:javascript
复制
['$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);

            });

        }
    };

}]

以此为模板:

代码语言:javascript
复制
<pre><code ng-bind-html="highlightedCode"></code></pre>
票数 3
EN

Stack Overflow用户

发布于 2014-02-26 14:52:01

基本上,您想将CodeValue传递给指令并在链接函数中操作它?

那麽:

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

代码语言:javascript
复制
    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

    }
};
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22043894

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档