2015-05-29 128 views
3

我想通过angular(HTML,CSS,JS)加载动态内容。我正在使用指令来动态加载HTML。以角度动态加载js脚本或js代码

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

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

+1

什么是用例?因为在我看来,这是一个糟糕的设计...... – deostroll

+0

@deostroll [here](http://stackoverflow.com/questions/30521546/made-angular-scope-available-in-django-templateresponse?noredirect=1 #comment49117361_30521546)是我正在尝试完成的完整流程 – saf

回答

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