我是棱角分明的新手。 所以这可能是一个非常基本的问题
我有外部API数据,这是用户生成的内容。 客户想要动态显示内容。在内容中,有一个脚本,其中创建了指令,我尝试使用ng-bind-html,但它不起作用。
<div ng-bind-html="myHTML"></div>
想要执行创建指令的脚本,并且应该在html内容中注入相同的指令。
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)
我添加了反斜杠以逃避单引号。
帮助在这里受到赞赏。
答案 0 :(得分:1)
演示:http://plnkr.co/edit/L8FWxNSQO6VAf5wbJBtF?p=preview
基于Add directive to module after bootstrap and applying on dynamic content
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));
}
}
}]);