我想根据指令名数组在我的页面中加载指令。
在我的主页:
<div component-loader></div>
指令:
myApp.directive('componentLoader', function($compile) {
var component = function(scope, element, attrs) {
$compile(element.contents())(scope);
}
return {
link: component,
replace: true,
scope: true,
template: '<div ng-repeat="component in components"><div {{component.directive}}></div></div>'
};
});
范围:
$scope.components = [{
directive: 'directive01'
},{
directive: 'directive02'
}]
我期待的是什么:
<div directive01></div>
<div directive02></div>
我得到了什么:
<div {{component.directive}}></div>
<div {{component.directive}}></div>
我做错了什么?
谢谢!
答案 0 :(得分:0)
绑定仅适用于属性内容,而不适用于属性名称(据我所知)。 相反,您可以使用无模板指令,并在链接函数中生成元素。
<div component-loader="components"></div>
您的链接功能
function(scope, element, attrs) {
var components = attrs.componentsLoader;
// Or use scope.components or scope.$parent.components depending on
// how your scopes are organised
angular.forEach(components, function (component) {
element.append(angular.element().attr(component.directive, '');
});
$compile(element.contents())(scope);
}
答案 1 :(得分:0)
仍然不是一个理想的解决方案,但它能做到我想要的:
myApp.directive('componentLoader', function($compile) {
var component = function(scope, element, attrs) {
scope.$watchCollection('components', function(a, b) {
var code = '';
var i;
for (i=0;i<scope.components.length;i++) {
code += '<div '+scope.components[i].directive+'></div>'
}
element.html($compile(code)(scope));
});
}
return {
link: component,
scope: true
};
});