如何创建一个指令来替换innerText


AngularJs: How to create a directive to replace innerText

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

$simple_question = "一列以60公里/小时的速度行驶的火车在9秒内穿过极点。火车的长度是多少?";

$programmimg_question = "[code]#include int main(int argc, char **argv) {printf("%c'n", **++argv);返回0;}][/代码";

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

这是我的代码在HTML

<div class="question-container">
   <code-highlighter> {{questionData.question}} </code-highlighter>
</div>

指令代码(不工作):

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

我是在angularjs中创建指令的新手,请给我一些资源或链接来实现上述问题,请帮助我解决这个问题。

Thanks, In advance.

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

你可以这样做:

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

那么你可以这样使用:

$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]内呈现HTML元素,使用以下链接函数:

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

这个<<p>看到,strong>更新演示。