我正在尝试根据指令名称的配置数组动态呈现指令。这在角度上可能吗?我还希望这些呈现的指令存在于单个父 dom 元素中,而不是每个都获得一个新的包装器(就像使用 ng-repeat 一样)
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>
这样,前置指令中的模板就不会被渲染。