首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AngularJs:如何创建替换innerText的指令

AngularJs:如何创建替换innerText的指令
EN

Stack Overflow用户
提问于 2014-07-21 18:28:19
回答 1查看 2.1K关注 0票数 0

我正在使用PHP+MySQL+AngularJs进行一个项目(在线考试,一个页面应用程序),其中有一个非常重要的部分,即“添加问题”。让我们以以下例子为例:

$simple_question =“一列以每小时60公里的速度行驶的列车在9秒内穿过一根杆子,火车的长度是多少?”;

$programmimg_question = "code#include int (int,char **argv) { printf("%c\n",**++argv);返回0;}/code";

所以您可以看到,每当插入编程语言问题时,我都会添加[code]....[/code],这样我就可以在显示问题的同时美化代码。我使用twitter引导程序,它有<code>标记来显示它们之间的代码。因此,我想要创建一个指令,它将把[code]替换为<code>,并在视图中呈现为HTML。

这是我的HTML代码

代码语言:javascript
复制
<div class="question-container">
   <code-highlighter> {{questionData.question}} </code-highlighter>
</div>

指令代码(不起作用):

代码语言:javascript
复制
app.directive('codeHighlighter', function ($compile) {
return {
    restrict: 'E',
    scope: {
        questions: "="
    },
    link: function (scope, element, attrs) {
        var html = element[0].outerHTML;
        var hasCodeElement = false;
        if(html.indexOf('[code]')!=-1) hasCodeElement = true;
        if(hasCodeElement) html = '<code>'+html+'</code>';
        var e = $compile(html)(scope);
        element.replaceWith(e);
    }
};
})

我是一个非常新的创建指令在天使,请给我一些资源或链接,以实现上述问题,请帮助我摆脱它。

谢谢,提前。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-21 23:00:35

你不需要$compile任何东西。只需根据指定的问题文本设置元素HTML,可以选择将[code]...[/code]替换为<code>...</code>

你可以这样做:

代码语言:javascript
复制
app.directive('question', function () {
    return {
        restrict: 'E',
        scope: {
            text: '='
        },
        link: function questionPostLink(scope, elem, attrs) {
            var html = scope.text.replace(
                    /\[code\](.*?)\[\/code\]/g,
                    '<code>$1</code>');
            elem.html(html);
        }
    };
});

然后你可以像这样使用它:

代码语言:javascript
复制
$scope.questions = [
    'This is a simple questions (without any [code]).',
    '[code]var str = \'This is a programming question.\';[/code]'
];

<question text="txt" ng-repeat="txt in questions"></question>

看,还有,这个短演示

更新:

为了能够按原样呈现[code]...[/code]元素,请使用以下链接函数:

代码语言:javascript
复制
link: function questionPostLink(scope, elem, attrs) {
    // Here, I assume that programming questions
    // always begin with [code] and end with [/code]
    var isProgramming = progRE.test(scope.text);

    if (!isProgramming) {
        var html = scope.text;
        elem.html(html);
    } else {
        var text = scope.text.replace(progRE, '$1');
        elem.html('<code></code>');
        elem.children().text(text);
    }
}

看,还有,这个更新演示

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

https://stackoverflow.com/questions/24872150

复制
相关文章

相似问题

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