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

时间:2014-07-21 18:28:19

标签: php angularjs twitter-bootstrap

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

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

$ programmimg_question =“[code] #include int main(int argc,char ** argv){printf(”%c \ n“,** ++ argv); return 0;} [/ code]”;

所以你可以看到,每当插入编程语言问题时我都会添加[code]....[/code],这样我就可以在显示问题时美化代码。我正在使用带有<code>标记的twitter bootstrap来显示它们之间的代码。所以我想创建一个指令,将[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中创建指令非常新,请给我一些资源或链接来解决上述问题,请帮我解决。

先谢谢。

1 个答案:

答案 0 :(得分:1)

您不需要$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>

另请参阅此 short demo


<强>更新

为了能够在[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);
    }
}

另请参阅此 updated demo