2013-10-04 32 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

哦,是的,你说得对。以为你的意思是后者。我的坏:) –

相关问题