我试图根据指令名称的配置数组动态呈现指令。这是可能的角?我也希望这些呈现的指令向单亲DOM元素,而不是每获得一个新的包装中的生活(你将与NG-重复)从父指令或控制器中的指令名称阵列呈现AngularJS指令
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>
这样,来自预定指令的模板就不会被渲染。
而不是用'element.append',你有没有考虑设置'限制:“ C''并更新元素上的类?这样可以将指令添加到现有的dom元素或创建新元素时。 – pedalpete