AngularJS + highlight.js(评估字符串与指令前pression) [英] AngularJS + highlight.js (to evaluate string with expression in directive)
问题描述
我想创建一个highlight.js指令,我有问题越来越瓦尔范围申请。
I am trying to create a highlight.js directive and I am having problems getting scope vars to apply.
<script src="http://code.jquery.com/jquery-1.8.2.min.js" ></script>
<link rel="stylesheet" href="http://yandex.st/highlightjs/7.3/styles/default.min.css">
<script src="http://yandex.st/highlightjs/7.3/highlight.min.js"></script>
<div ng-app="app">
<div ng-controller="MyCtrl">
<snippet><script src="{{src}}"></script></snippet>
{{src}}
</div>
</div>
function MyCtrl($scope) {
$scope.src = "foo.js";
}
app.directive('snippet', ['$timeout', function($timeout) {
var template = '<pre><code></code></pre>';
return {
restrict: 'E',
compile: function(tElement, tAttrs, transclude) {
var rawCode = tElement.text();
tElement.html(template);
return function(scope, element, attrs) {
$timeout(function() {
scope.$apply(function() {
var formattedCode = hljs.highlightAuto(rawCode);
$(element).find('code').html(formattedCode.value);
});
}, 0);
}
}
}
}]);
下面是小提琴: http://jsfiddle.net/dkrotts/RE7Jj/5/
正如你所看到的,$ scope.src不片段内部施加它的价值。我在做什么错了?
As you can see, $scope.src is not applying its value inside the snippet. What am I doing wrong?
推荐答案
The key is you should use $interpolate instead of $compile
的说明$插值
与编译标记中的字符串转换为插补功能。这个
服务由数据绑定的HTML $编译服务使用。看到
$ interpolateProvider用于配置插标记。
Compiles a string with markup into an interpolation function. This service is used by the HTML $compile service for data binding. See $interpolateProvider for configuring the interpolation markup.
当您使用$ complie,它会变成你的字符串转换成元素。
When you use $complie, it will turn your string into element.
的说明$编译
编译一段HTML字符串或DOM 的成模板并产生
模板函数,那么它可以用来链接的范围和
模板在一起。
Compiles a piece of HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.
(说实话,我真的不明白,直到描述尝试一下。)
(To be honest, I don't really understand the description until trying it out.)
下面是工作普拉克
app.controller('MainCtrl', function($scope) {
$scope.cdnPath = "//path/to/cdn/";
$scope.version = "1.0";
});
app.directive('snippet', ['$timeout', '$interpolate', function($timeout, $interpolate) {
return {
restrict: 'E',
template:'<pre><code ng-transclude></code></pre>',
replace:true,
transclude:true,
link:function(scope, elm, attrs){
var tmp = $interpolate(elm.find('code').text())(scope);
$timeout(function() {
elm.find('code').html(hljs.highlightAuto(tmp).value);
}, 0);
}
};
}]);
这篇关于AngularJS + highlight.js(评估字符串与指令前pression)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!