2013-10-04 35 views
2

當我使用$ compile爲我的指令創建一個動態模板時,我遇到了作用域丟失的問題。請參閱下面的代碼(爲了清晰起見而修剪):

(function() { 
'use strict'; 

angular.module('cdt.dm.directives').directive('serviceSources', ['$http', '$templateCache', '$compile', '$parse', 
function ($http, $templateCache, $compile, $parse) { 
    return { 
     restrict: 'E', 
     replace: true, 
     scope: { 
      type: '=', 
      sources: '=' 
     }, 
     link: function (scope, element, attr) { 
      var template = 'Template_' + scope.type + '.html'; 

      $http.get(template, { cache: $templateCache }).success(function (tplContent) { 
       element.replaceWith($compile(tplContent)(scope)); 
      }); 

      $compile(element.contents())(scope); 
     } 
    } 
} 
]) 
})(); 

工作和html模板被加載。

HTML模板看起來像:

<table> 
<thead> 
    <tr> 
     <th>File</th>   
    </tr> 
</thead> 
<tbody data-ng-reapeat="src in sources"> 
    <tr> 
     <td>{{src.fileName}}</td> 
    </tr> 
</tbody> 

源是具有兩個元件的陣列。在指令的範圍內,它是絕對正確的,但在模板中,ng-repeat不起作用(我猜是因爲在這個階段源未定義)。

有人知道我在做什麼錯嗎?

+3

我不知道你是否可以使用'templateUrl'來代替? –

+0

不,模板需要是動態的,基於傳遞給作用域'type'變量的值。所以我不能使用templateUrl。 – Sam

+0

我已根據您的建議編輯了原始代碼,謝謝。 – Sam

回答

2

我覺得有一個錯字:ng-repeat代替data-ng-reapeat,並且ng-repeat應放在<tr>

<table> 
<thead> 
    <tr> 
     <th>File</th>   
    </tr> 
</thead> 
<tbody> 
    <tr ng-repeat="src in sources"> 
     <td>{{src.fileName}}</td> 
    </tr> 
</tbody> 

注意$http.get是ASYN,記得裏面包裹的scope.$apply代碼。你應該這樣修改你的代碼:

link: function (scope, element, attr) { 
      var template = 'Template_' + scope.type + '.html'; 

      $http.get(template, { cache: $templateCache }).success(function (tplContent) { 
       scope.$apply(function(){ 
       element.replaceWith(tplContent); 
       $compile(element)(scope); 
       //Or 
       //element.html(tplContent); 
       //$compile(element.contents())(scope); 
       }); 
      }); 
     } 
+0

ng-repeat和data-ng-repeat是可以互換的。所有指令都是一樣的,它們都可以有數據前綴,甚至是自定義指令。 –

+0

@ francisco.preller:如果你仔細觀察,你會看到'reapeat'而不是'repeat' –

+0

哦,是的,你說得對。以爲你的意思是後者。我的壞:) –

相關問題