gpt4 book ai didi

javascript - AngularJS + highlight.js(用指令中的表达式评估字符串)

转载 作者:数据小太阳 更新时间:2023-10-29 05:04:25 25 4
gpt4 key购买 nike

我正在尝试创建一个 highlight.js 指令,但在应用范围变量时遇到了问题。

<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>&lt;script src=&quot;{{src}}&quot;&gt;&lt;/script&gt;</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);
}
}
}
}]);​

这是 fiddle :http://jsfiddle.net/dkrotts/RE7Jj/5/

如您所见,$scope.src 并未在代码片段中应用其值。我做错了什么?

最佳答案

关键是你应该使用$interpolate而不是 $compile

Description of $interpolate

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 时,它​​会将您的字符串转换为元素。

Description of $compile

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.

(老实说,在尝试之前我并不真正理解描述。)

这是工作 plunk

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

关于javascript - AngularJS + highlight.js(用指令中的表达式评估字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13385535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com