簡體   English   中英

動態創建和加載角度指令

[英]Dynamically Create and Load Angular Directive

在我的應用程序中,我有一個自定義指令名稱列表。

$scope.data =["app-hello","app-goodby","app-goodafter"];

此數組中的每個名稱都是我創建的一個指令。

var app = angular.module('app',[]).controller('mainCtrl',function($scope){
 $scope.data =["app-hello","app-goodby","app-goodafter"];
}).directive('appHello',function(){
 return {
  restrict:'EA',
  template:'<h1>Hello Directive</h1>'
};
}).directive('appGoodbye',function(){
return {
 restrict:'EA',
template:'<h1>GoodBye</h1>'
 };
}).directive('appGoodafter',function(){
  return{
restrict:'EA',
template:'<h1>Good Afternoon</h1>'
};
});

現在我想在視圖中加載帶有ng-repeat指令,例如因為我使用EA restrict for directive可以在ng-repeat創建指令,如下所示:

<div ng-repeat="d in data" >
  <div {{d}}></div>
</div>

但這種方式不起作用。 所以真正的問題是,如果我有指令列表如何使用ng-repeat加載此指令。對於這種情況,我創建了一個jsbin 謝謝。

你需要一個“master”指令,將$compile HTML(可選地包含指令)到Angular-aware模板中,然后將編譯后的元素鏈接到$ scope:

app.directive('master', function ($compile) {
    return {
        restrict: 'A',
        link: function postLink(scope, elem, attrs) {
            attrs.$observe('directive', function (dirName) {
                if (dirName) {
                    var compiledAndLinkedElem =
                            $compile('<div ' + dirName + '></div>')(scope);
                    elem.html('').append(compiledAndLinkedElem);
                }
            });
        }
    };
});

<div master directive="{{dir}}" ng-repeat="dir in ['dir1', 'dir2', 'dir3']"></div>

另見這個簡短的演示

你可以這樣做:

指示:

app.directive('compile',function($compile){
  return{
    restrict:'A',
    template: '<div></div>',
    link:function(scope,elem,attrs){
      scope.name = attrs.compile;
      elem.children('div').attr(scope.name,'');
      $compile(elem.contents())(scope);
    }
  };
});

HTML:

  <div ng-repeat="d in data" compile="{{d}}">
  </div>

Jsbin: http ://jsbin.com/wofituye/4/edit

我實際上更喜歡創建只包含指令的模板。 然后你可以使用ng-include這使你能夠輕松地將范圍變量傳遞給動態選擇的指令。

這是我的小部件代碼前例:

<div ng-repeat="widget in widgets track by $index" ng-include="widget.url" class="widget-container" ng-class="widget.widget_type.config.height +' ' + widget.widget_type.config.width">
</div>

然后我將widget.url設置為只包含正確指令的模板。

我可以在我的指令中這樣做:

<custom-widget ng-attr-widget="widget"></custom-widget>

然后我也可以訪問動態變量,所以我也可以訪問配置細節,而不必動態生成HTML字符串並編譯它們。 不是一個完美的解決方案,但我個人習慣使用上面提到的其他方法,並發現這更適合我的需求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM