gpt4 book ai didi

javascript - 以 Angular 动态加载js脚本或js代码

转载 作者:行者123 更新时间:2023-12-03 12:29:55 26 4
gpt4 key购买 nike

我想通过 angular (HTML, CSS, JS) 加载动态内容。我正在使用指令动态加载 HTML。

app.directive("bindCompiledHtml", function($compile, $timeout) {
return {
template: '<div></div>',
scope: {
rawHtml: '=bindCompiledHtml'
},
link: function(scope, elem, attrs) {
scope.$watch('rawHtml', function(value) {
if (!value) return;
// we want to use the scope OUTSIDE of this directive
// (which itself is an isolate scope).
var newElem = $compile(value)(scope.$parent);
elem.contents().remove();
elem.append(newElem);
});
}
};
});



<div bind-compiled-html="content"></div>

如果内容仅包含 HTML,则它会成功呈现它,但如果它包含 CSS/Script,则不会。

上面的指令不会呈现下面的代码。

'<link rel="stylesheet" href="/static/engine/css/jquery.bxslider.less"><script src="/static/engine/js/jquery.bxslider.js"></script><style></style><script  type="text/javascript">function mytest(){$(\'.bxslider\').bxSlider();   }</script><ul class="bxslider"><li ng-repeat=\'brainfact in brainfacts\'><img src="{$ brainfact.content[\'image\'] $}" /></li></ul>'

将呈现以下代码:

 '<ul class="bxslider"><li ng-repeat=\'brainfact in brainfacts\'><img src="{$ brainfact.content[\'image\'] $}" /></li></ul>'

演示插件 - http://plnkr.co/edit/QG5IbaNfhNDrIyRbXEGx?p=preview

最佳答案

我修复了你的样本 here .

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
$scope.brainfactTabData = '<script type="text/javascript" >alert(new Date());</script><div></div><script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script><span>working</span>'

});

app.directive("bindCompiledHtml", function($compile, $timeout, $sce) {
return {
template: '<div ng-bind-html="content"></div>',
scope: {
rawHtml: '=bindCompiledHtml'
},
link: function(scope, elem, attrs) {
scope.$watch('rawHtml', function(value) {
if (!value) return;

elem.html(value);

$compile(elem.contents())(scope.$parent);
});
}
};
});

关于javascript - 以 Angular 动态加载js脚本或js代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30522801/

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