以角度动态加载js脚本或js代码

时间:2015-05-29 06:41:17

标签: javascript angularjs

我想通过angular(HTML,CSS,JS)加载动态内容。我正在使用指令动态加载HTML。

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>

如果内容只包含HTML,那么它会成功呈现它,但如果它包含CSS / Script则不是。

以上指令不会渲染以下代码。

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

将呈现以下代码:

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

1 个答案:

答案 0 :(得分:0)

我修复了您的示例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);
      });
    }
  };
});