我正在尝试根据指令名称的配置数组动态渲染指令。在Angular中是否可能实现这一点?我还希望这些已呈现指令驻留在单个父DOM元素内,而不是每个都获得一个新包装(就像您使用ng-repeat时一样)。
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>
使用这种方法,来自预置指令的模板将不会被渲染。
restrict: 'C'
并更新元素的类名,而不是使用element.append
?这样指令就可以添加到现有的 DOM 元素上或在创建新元素时使用。 - pedalpete