Skip to content Skip to sidebar Skip to footer

Ng-bind-html Doesn't Work With Script

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 con

Solution 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><scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script><scriptsrc="./app.js"></script></head><bodyng-app="demo"><divng-controller="mainController"><external-htmlexternal-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));


    }
  }
}]);

Post a Comment for "Ng-bind-html Doesn't Work With Script"