问题
I am new to angular js. So this might be very basic question
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>
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.
help is appreciated here.
回答1:
Demo: http://plnkr.co/edit/L8FWxNSQO6VAf5wbJBtF?p=preview
Base on 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));
}
}
}]);
来源:https://stackoverflow.com/questions/42749029/ng-bind-html-doesnt-work-with-script