在Angular中动态加载JS脚本或JS代码

3
我希望通过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/脚本,则不会。

上述指令将无法呈现下面的代码。

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

演示 Plunker - http://plnkr.co/edit/QG5IbaNfhNDrIyRbXEGx?p=preview


1
什么是使用案例?因为在我看来,这是一个糟糕的设计... - deostroll
@deostroll 这里是我正在尝试做的完整流程:http://stackoverflow.com/questions/30521546/made-angular-scope-available-in-django-templateresponse?noredirect=1#comment49117361_30521546 - saf
1个回答

0

我修复了你的示例这里

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);
      });
    }
  };
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接