2013-08-22 36 views
2

我要動態添加HTML內容與angularJs,但得到和錯誤:如何動態地添加HTML內容與AngularJs

"$compile is not defined" 

什麼能是什麼原因?

代碼

<td ng-repeat="user in users[0].yds" data-title="'Timeline'" sortable="timeline" style="text-align: center" > 
    <div class="circle_dynamic"></div> 
</td> 


angular.module('elnApp') 
    .controller('ProgramtableCtrl', function ($scope, $location, $filter, ngTableParams,  
    programTableService) { 
     for(var i=0; i<=$scope.users[0].projects.length; i++){ 
      for(var j=0; j<$scope.users[0].projects[i].results.length; j++){ 

       if($scope.users[0].projects[i].results[j] == 0){ 

        $(".circle_dynamic").html(
         $compile(
         "" 
        )(scope) 
        ); 
        console.log('rm') 
       }else{ 

        $(".circle_dynamic").html(
         $compile(
         "<i ng-class='circle_class' style='position: absolute;'></i>" 
        )(scope) 
        ); 
        console.log('add') 
       } 
      } 

     } 

    }, true); 

}}); 

如何動態地添加HTML內容?請幫忙

+0

這是什麼代碼?在指令中?在控制器?向我們展示如何初始化它。 – package

+0

這是在控制器 – user2680731

+0

爲什麼你需要調用$ compile?即使你這樣做,你也應該在指令中做,而不是在控制器中。 – 0xc0de

回答

0

這裏不需要撥打$compile

注意:硬編碼索引$scope.users[0].projects.length對我來說似乎在邏輯上不正確,您確定要這麼做嗎?

代碼中的這些行非常混亂。如果您知道用戶的數據結構(即用戶,項目和結果之間的關係)以及您想實現的目標,那麼您將更容易得到答案。

for(var i=0; i<=$scope.users[0].projects.length; i++){ 
    for(var j=0; j<$scope.users[0].projects[i].results.length; j++){ 

下列溶液是假設

users是用戶的陣列。

每個user有很多projects,所以user.projects是一個數組。

如果存在每個結果,您想要爲每個結果顯示class="circle_class"

有了這些假設,以下應該就足夠了。

<td ng-repeat="user in users[0].yds" 
    data-title="'Timeline'" 
    sortable="timeline" 
    style="text-align: center" > 
    <div ng-repeat="project in user.projects"> 
    <div ng-repeat="result in project.results" 
     ng-show="result"> 
     <i ng-class='circle_class' style='position: absolute;'></i> 
     </div> 
    </div> 
</td> 
+0

什麼是我,j?混淆部分是你迭代用戶並顯示第一個用戶的項目結果。如果你真的想要,然後定義'var projectOwner = $ scope.users [0]',並使用它,這樣就會清楚。 – 0xc0de

+0

如果結果值是1,我想顯示它,我該怎麼做? – user2680731

+0

如果每個用戶的每個項目的結果爲1(非零),則此代碼將顯示每個結果的圖標。如果結果爲0,它不會顯示圖標。 – 0xc0de

0

如果你只是想添加html內容ng-bindHtmlUnsafe會做伎倆。

在HTML

<div class="circle_dynamic" ng-bindHtmlUnsafe={{expression}}></div> 

在控制器

$scope.expression="<i ng-class='circle_class' style='position: absolute;'></i>" 

查看文檔here

+0

文檔沒有樣本,我不能清除它 – user2680731

+0

你不應該嘗試修改控制器中的DOM。 – 0xc0de

0

在angularjs,作爲最佳實踐,你應該使用指令對DOM操作

你爲什麼需要編譯它嗎?

0

「$ compile is not defined」是因爲您忘記將其注入控制器而發生的。

使用$ compile動態添加HTML內容是可以的。但是不要在你的控制器裏做。做一個指令。