2014-09-24 42 views
1

我想注入一個html,這是渲染Django模板的結果。 Django模板:AngularJS - 樣式不適用於附加的html

class CView(View): 
    def get(self, request): 
     return render_to_response('my_template.html', {},content_type="application/json") 

當硬編碼時,生成的html正確顯示。 我想將接收到的html代碼注入到div中。問題在於自舉手風琴部件不顯示。我只拿到文字。

代碼在角控制器:

$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文件,則相同的代碼呈現效果很好。 我正在使用angular的bootstrap

回答

2

有兩個可能的回答這個問題:

DEMO

[如果您dataService.getHtml()實際上是從它返回一個HTML的URL服務器請求數據,並且它不是在服務中操作html本身,那麼您可以安全地使用ng-include指令:

<div ng-include="'http://somewhere/mytemplate.html'"></div> 

如果是這種情況,那麼您不需要實際使用$compile服務並手動將其添加到html中。

[如果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); 
     } 
     }); 
    } 
    }); 
1

您必須使用角度的$ compile函數來識別注入的html代碼中的指令。