Mih*_*lcu 4 javascript angularjs angularjs-directive
我正试图在我的角度应用程序中使用prismjs
这是我到目前为止所得到的
app.directive('nagPrism', [function() {
return {
restrict: 'A',
transclude: true,
scope: {
source: '='
},
link: function(scope, element, attrs, controller, transclude) {
if(!scope.source) {
transclude(function(clone) {
element.html(clone);
Prism.highlightElement(element.find("code")[0]);
});
} else {
scope.$watch(function() {return scope.source;}, function(v) {
if(v) {
Prism.highlightElement(element.find("code")[0]);
}
});
}
},
template: "<code ng-bind='source'></code>"
};
}]);
Run Code Online (Sandbox Code Playgroud)
如果我有这样的东西,这将有效
<!-- This works -->
<pre nag-prism source="code" class="language-css"></pre>
Run Code Online (Sandbox Code Playgroud)
但我想让它也适合这样的事情
<pre nag-prism class="language-css">
<code>body {
color: red;
}
{{code}}
</code>
</pre>
Run Code Online (Sandbox Code Playgroud)
为方便起见,我做了一个plunkr
任何提示?
据我所知,你的目标是建立一个突出代码的指令,这些代码既可以作为常量给定,也可以通过变量或上面两个混合使用.如果您没有附上帖子的语法,这里有解决方案.
主要问题是在应用Prism高亮功能之前,需要编译代码模板以便将{{variables}}更改为它们的值.在您的解决方案中,突出显示功能应用于原始模板
我们的想法是将绑定类型从'='更改为'@',并在所有情况下将源代码作为属性传递.
旧约束:
scope: {
source: '='
}
Run Code Online (Sandbox Code Playgroud)
新绑定:
scope: {
source: '@'
}
Run Code Online (Sandbox Code Playgroud)
角度文件:
@或@attr - 将本地范围属性绑定到DOM属性的值.结果总是一个字符串,因为DOM属性是字符串.如果未指定attr名称,则假定属性名称与本地名称相同.范围的给定和窗口小部件定义:{localName:'@ myAttr'},然后窗口小部件范围属性localName将反映hello {{name}}的内插值.随着name属性的更改,widget命名空间上的localName属性也会更改.从父作用域(而不是组件作用域)读取名称.
更新了html示例(请注意,第一个示例中的旧绑定也已更改!):
<!-- This works -->
<pre nag-prism source="{{code}}" class="language-css"></pre>
<!-- Now this works either! -->
<pre nag-prism source="body {
color: red;
}
{{code}}" class="language-css"></pre>
Run Code Online (Sandbox Code Playgroud)
完整更新的指令代码:
app.directive('nagPrism', [function() {
return {
restrict: 'A',
scope: {
source: '@'
},
link: function(scope, element, attrs) {
scope.$watch('source', function(v) {
if(v) {
Prism.highlightElement(element.find("code")[0]);
}
});
},
template: "<code ng-bind='source'></code>"
};
}]);
Run Code Online (Sandbox Code Playgroud)
你可以在这里找到工作解决方案:工作样本
编辑:指令已更新,以满足以下评论中的目标
为了正确显示已删除的内容,必须手动编译.它会导致指令代码发生一些变化(如果版本不为空且未定义源,则下面的版本使用已转换的内容):
app.directive('nagPrism', ['$compile', function($compile) {
return {
restrict: 'A',
transclude: true,
scope: {
source: '@'
},
link: function(scope, element, attrs, controller, transclude) {
scope.$watch('source', function(v) {
element.find("code").html(v);
Prism.highlightElement(element.find("code")[0]);
});
transclude(function(clone) {
if (clone.html() !== undefined) {
element.find("code").html(clone.html());
$compile(element.contents())(scope.$parent);
}
});
},
template: "<code></code>"
};
}]);
Run Code Online (Sandbox Code Playgroud)
下面的示例添加了绑定到输入的代码块,以显示链接工作:改进的示例
| 归档时间: |
|
| 查看次数: |
4367 次 |
| 最近记录: |