我正在使用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代码
<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);
}
};
})我是一个非常新的创建指令在天使,请给我一些资源或链接,以实现上述问题,请帮助我摆脱它。
谢谢,提前。
发布于 2014-07-21 23:00:35
你不需要$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]元素,请使用以下链接函数:
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);
}
}看,还有,这个更新演示。
https://stackoverflow.com/questions/24872150
复制相似问题