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));