ng-bind-html不适用于脚本 [英] ng-bind-html doesn't work with script
本文介绍了ng-bind-html不适用于脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是angular js的新手. 因此,这可能是一个非常基本的问题
I am new to angular js. So this might be very basic question
我有外部API数据,它是用户生成的内容. 客户端希望动态显示内容.在内容中,有一个在其中创建指令的脚本,我尝试使用ng-bind-html,但它不起作用.
I have external API data which is a user generated content. The client wants to dynamically show the content. In content, there is script in which directive is created, I tried using ng-bind-html but it doesn't work.
<div ng-bind-html="myHTML"></div>
要执行在其中创建指令的脚本,并且应该在html内容中插入相同的指令.
want to execute the script in which directive is created and same directive should be injected in html content.
var data = '<script> var app = angular.module(\'main\', []);' +
'app.directive(\'slideImageComparison\', function () {return { restrict: \'E\', scope: { imageInfo: \'=info\'}, link: function (scope, elem, attr) { console.log(\'directive called\');' +
'},template: \'<div class="slide-comb"> test </div>\'' +
'}; }); </script> <slide-image-comparison></slide-image-comparison>';
$scope.myHTML= $sce.trustAsHtml(data)
我添加了反斜杠以转义单引号.
I added backslash to escape a single quote.
在此感谢您的帮助.
推荐答案
演示: http://plnkr.co/edit/L8FWxNSQO6VAf5wbJBtF?p=preview
html:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<script src="./app.js"></script>
</head>
<body ng-app="demo">
<div ng-controller="mainController">
<external-html external-data="external"></external-html>
</div>
</body>
</html>
js:
var module1 = angular.module("demo", []);
module1.controller("mainController", ["$scope", function(sp) {
var external = `<script>
module1.lazyDirective('sl', function () {
return { restrict:'E',
scope: { imageInfo: '=info'},
link: function (scope, elem, attr) {
console.log('directive called');
},
template: '<div class="slide-comb"> test </div>'};
});
</script>
<sl></sl>`;
sp.external = external;
}]).config(function($compileProvider) {
module1.lazyDirective = $compileProvider.directive;
}).directive('externalHtml', ["$parse", "$compile", function($parse, $compile) {
return {
restrict: 'E',
link: function(scope, element, attrs) {
const data = $parse(attrs.externalData)(scope);
const el = document.createElement('div');
el.innerHTML = data;
const scripts = el.getElementsByTagName("script");
for (let i in scripts) {
console.log(scripts[i].textContent)
eval(scripts[i].textContent);
}
element.append($compile(data)(scope));
}
}
}]);
这篇关于ng-bind-html不适用于脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文