2013-08-31 32 views
4

我試圖根據指令名稱的配置數組動態呈現指令。這是可能的角?我也希望這些呈現的指令向單親DOM元素,而不是每獲得一個新的包裝中的生活(你將與NG-重複)從父指令或控制器中的指令名稱陣列呈現AngularJS指令

http://jsfiddle.net/7Waxv/

var myApp = angular.module('myApp', []); 

myApp.directive('one', function() { 
    return { 
     restrict: 'A', 
     template: '<div>Directive one</div>' 
    } 
}); 

myApp.directive('two', function() { 
    return { 
     restrict: 'A', 
     template: '<div>Directive two</div>' 
    } 
}); 

function MyCtrl($scope) { 
    $scope.directives = ['one', 'two']; 
} 

<div ng-controller="MyCtrl"> 
    <div ng-repeat="directive in directives"> 
     <div {{directive}}></div> 
    </div> 
</div> 

編輯: 自發布此,我我也試過了:

.directive('parentDirective', function() { 
    return { 
    restrict: 'A', 
    replace: true, 
    link: function (scope, element) { 
     scope.directives = ['one', 'two']; 
     for (var i = 0; i < scope.directives.length; i++) { 
     element.prepend('<div ' + scope.directives[i] + '></div>') 
     } 
    } 
    }; 
}); 

<div parent-directive></div> 

這樣,來自預定指令的模板就不會被渲染。

回答

5

這裏是我想出了(花了很長時間)...該解決方案是非常多才多藝不過,您可以隨意修改$scope.directives數組,並且指令將被動態編制。您還可以指向當前範圍中的任何特定屬性以從中檢索指令列表。

Demo link

app.js

var myApp = angular.module('myApp', []); 

myApp.directive('one', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     template: '<div>Directive one</div>' 
    } 
}); 

myApp.directive('two', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     template: '<div>Directive two</div>' 
    } 
}); 

myApp.directive('dynamic', function ($compile, $parse) { 
    return { 
    restrict: 'A', 
    replace: true, 
    link: function (scope, element, attr) { 
     attr.$observe('dynamic', function(val) { 
     element.html(''); 
     var directives = $parse(val)(scope); 
     angular.forEach(directives, function(directive) { 
      element.append($compile(directive)(scope)); 
     }); 
     }); 
    } 
    }; 
}); 

function MyCtrl($scope) { 
    $scope.directives = ['<one/>', '<two/>']; 
    $scope.add = function(directive) { 
     $scope.directives.push(directive); 
    } 
} 

的index.html

<div ng-controller="MyCtrl"> 
    <div dynamic="{{directives}}"></div> 
    <button ng-click="add('<one/>')">Add One</button> 
    <button ng-click="add('<two/>')">Add One</button> 
</div> 
+1

而不是用'element.append',你有沒有考慮設置'限制:「 C''並更新元素上的類?這樣可以將指令添加到現有的dom元素或創建新元素時。 – pedalpete

0

所以在第二次嘗試會工作過我用$編譯的前置指令,像這樣:

.directive('parentDirective', function($compile) 
    .... 
element.prepend($compile('<div ' + scope.directives[i] + '"></div>')(scope));