[英]AngularJS - Styles not applying on appended html
我想注入一個渲染django模板的結果的html。 Django模板:
class CView(View):
def get(self, request):
return render_to_response('my_template.html', {},content_type="application/json")
在硬編碼時,生成的html正確顯示。 我想將收到的html代碼注入到div中。 問題是bootstrap手風琴組件不顯示。 我只收到文字。
角度控制器中的代碼:
$scope.myHTML = '<div>Loading..<div>';
$scope.to_trusted = function (html_code) {
return $sce.trustAsHtml(html_code);
}
dataService.getMyHtml().success(function (data) {
$timeout(function () {
$scope.$apply(function () {
$scope.myHTML = data;
})
}, 0);
}).error();
HTML代碼:
<div ng-bind-html="to_trusted(myHTML)"></div>
myHTML包含這樣的內容:
<div class="col-sm-3 col-md-2 sidebar">
<accordion close-others="true">
<accordion-group>
<accordion-heading>
Items One <i class="pull-right glyphicon"
ng-class="{'glyphicon-chevron-down': status.open, 'glyphicon-chevron-right': !status.open}"></i>
</accordion-heading>
<ul class="nav nav-sidebar">
<li><a href="#/one">One 1</a></li>
<li><a href="#/two">One 2</a></li>
</ul>
</accordion-group>
<accordion-group>
<accordion-heading>
Items Two <i class="pull-right glyphicon"
ng-class="{'glyphicon-chevron-down': status.open, 'glyphicon-chevron-right': !status.open}"></i>
</accordion-heading>
<ul class="nav nav-sidebar">
<li><a href="#/one">Two 1</a></li>
<li><a href="#/two">Two 2</a></li>
</ul>
</accordion-group>
</accordion>
</div>
上面的代碼只是呈現為垂直列表菜單,但沒有手風琴。 如果作為靜態html文件加載,相同的代碼呈現正常。 我正在使用角度的引導程序 。
這個問題有兩種可能的答案:
[ 1 ]如果你的dataService.getHtml()實際上是從一個返回html的url請求來自服務器的數據,並且它沒有在服務中操縱html本身,那么你可以安全地使用ng-include
指令:
<div ng-include="'http://somewhere/mytemplate.html'"></div>
如果是這種情況,那么您不需要實際使用$compile
服務並在html中手動添加它。
[ 2 ]如果您的dataService不需要來自服務器的請求並且正在服務本身內構建html內容,那么您需要使用$compile
服務。 為此,您需要創建一個編譯html內容的指令並手動添加html本身。
HTML
<div compile-html="html"></div>
JAVASCRIPT
.service('dataService', function($http, $q) {
this.getHtml = function() {
var deferred = $q.defer();
$http.get('accordion.tpls')
.success(function(template) {
deferred.resolve(template + '<h1>Added another html in here</h1>');
}, deferred.reject);
return deferred.promise;
};
})
.controller('Ctrl', function($scope, dataService) {
dataService.getHtml().then(function(template) {
$scope.html = template;
});
})
.directive('compileHtml', function($compile) {
return function(scope, elem, attr) {
scope.$watch(attr.compileHtml, function(value) {
if(value) {
elem.html(value);
$compile(elem.contents())(scope);
}
});
}
});
你必須在angular中使用$ compile函數才能識別注入的html代碼中的指令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.