Load js script or js code dynamically in angular

I want to load dynamic content via angular (HTML, CSS, JS). I am using a directive to load HTML dynamically.

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>

      

If the content only contains HTML, it renders it successfully, but if it contains CSS / Script, it doesn't.

This below code will not appear above the directive.

'<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>'

      

Will display this code below:

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

      

demo plunker - http://plnkr.co/edit/QG5IbaNfhNDrIyRbXEGx?p=preview

+3


source to share


1 answer


I've installed your sample 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);
      });
    }
  };
});

      

0


source







All Articles