从父指令或控制器中的指令名称数组呈现AngularJS指令
Rendering AngularJS directives from array of directive names in a parent directive or controller
我正在尝试基于指令名称的配置数组动态呈现指令。这在角度上可能吗?我还希望这些呈现的指令生活在一个单独的父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>
这样,预处理指令中的模板就不会被呈现。
下面是我的想法(花了很长时间)。。。不过,该解决方案非常通用,您可以随意修改$scope.directives
阵列,指令将动态生成。您还可以指向当前作用域中的任何特定属性以从中检索指令列表。
演示链接
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>
因此,如果我在前缀指令上使用$compile,第二次尝试就会成功,比如:
.directive('parentDirective', function($compile)
....
element.prepend($compile('<div ' + scope.directives[i] + '"></div>')(scope));
相关文章:
- 如何使用angular指令从html中获取数组
- 如何从 Angular ng-repeat 指令中检索数组中的某些索引
- 如何使用.指令跟踪ngModel数组项的行为
- 如何在angularjs中对指令内部的JSON数组使用过滤器
- 父数组中每个值的 Angular 指令保持同步
- AngularJs:迭代指令内的数组以创建嵌套的指令集
- 如何从自定义指令获取传递的属性并将它们收集到数组中以显示到模板中
- 创建 AngularJS 指令,如 ngModel 用于数组
- 在HandsonTable Angular指令中使用数组中的数据
- 从数组指令中删除重复项
- 角度JS并将复杂对象数组作为属性传递给指令
- AngularJS - 将多个 get 请求收集到 json 数组中,然后传递给指令
- 无法将数组传递给角度指令
- 使用指令器的数组
- 为 javascript 数组创建 angularjs 指令,将其转换为复选框列表
- 通过 Angular 指令在 html 模板中迭代配置数组
- 推送到数组不会通过ng repeat指令更新视图列表
- 从父指令或控制器中的指令名称数组呈现AngularJS指令
- 如何使用AngularJS ngShow指令仅在元素位于数组中时显示
- 在数组上重复的Angularjs指令