2013-10-03 33 views
2

我有一個指令定義爲

Application.Directives.directive('listview', function() { 
    return { 
     restrict: 'EAC', 
     templateUrl: 'directives/listview/view.html' 
    }; 
}); 

然後想從這樣的

<div class="{{directiveName}}"> 
</div> 

主要觀點包括它放在directiveName等於「列表顯示」。但是,它不起作用。它產生下面的代碼,但列表視圖指令中沒有加載

<div class="listview"> 
</div> 

然而,當我直接鍵入上面生成的代碼到主模板,它確實負載指令。怎麼來的?我怎樣才能使它工作?

回答

2

所以我找到了一種方法。你想要的是這樣的東西

<div {{directiveNameInScope}}></div> 

但是,再次,這是行不通的。所以我創建了一個指令來爲你做。它的工作原理就像

<div loaddirective="directiveNameInScope"></div> 

其中loaddirective指令看起來像

Application.Directives.directive('loaddirective', function($compile) { 
    return { 
     restrict: 'A', 
     scope: { loaddirective : "=loaddirective" }, 
     link: function($scope, $element, $attr) { 
      var value = $scope.loaddirective; 
      if (value) { 
       // Load the directive and make it reactive 
       $element.html("<div "+value+"></div>"); 
       $compile($element.contents())($scope); 
      } 
     }, 
     replace: true 
    }; 
}); 

我把它掛在github上的位置:https://github.com/willemmulder/loaddirective