Javascript 在AngularJS中使用元数据动态插入指令?
我想定义元数据,它将根据“type”值动态使用正确的指令: 然后Javascript 在AngularJS中使用元数据动态插入指令?,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我想定义元数据,它将根据“type”值动态使用正确的指令: 然后 <li ng-repeat="item in items" {{type}}> {{value}} </li> {{value}} 我已经创建了一个JSFIDLE。到目前为止我还没有成功 这可能吗?我将如何完成此任务?以下是解决此问题的另一种方法: 使用ngSwitch在类型和指令之间映射 <li ng-repeat="item in items"> <div ng
<li ng-repeat="item in items" {{type}}>
{{value}}
</li>
{{value}}
我已经创建了一个JSFIDLE。到目前为止我还没有成功
这可能吗?我将如何完成此任务?以下是解决此问题的另一种方法: 使用ngSwitch在类型和指令之间映射
<li ng-repeat="item in items">
<div ng-switch on="item.type">
<div ng-switch-when="type-one" directive-one>
</div>
<div ng-switch-when="type-two" directive-two>
</div>
<div ng-switch-when="type-three" directive-three>
</div>
</div>
</li>
但是,如果确实需要在元数据中定义该指令,则可以添加一个指令,该指令将使用适当的指令生成div元素
angular.module('myApp').directive('dynamicDirective', function($compile) {
return {
restrict: 'A',
link: function (scope, ele) {
//add a child div element that contains the directive specified in the type property
var itemEl = angular.element('<div>').attr(scope.item.type,'');
$compile(itemEl)(scope);
ele.append(itemEl);
}
};
});
angular.module('myApp')。指令('dynamicDirective',函数($compile){
返回{
限制:“A”,
链接:功能(范围、要素){
//添加包含type属性中指定的指令的子div元素
var itemEl=angular.element(“”).attr(scope.item.type“”);
$compile(itemEl)(范围);
附加元素(itemEl);
}
};
});
谢谢你的建议!我认为第二种方法将导致一个单一指令,支持可能更好的多个指令。例如,这可能导致
和
而不是单独的指令封装它们自己的特定功能。第二种方法只是编译HTML,以便动态选择附加到元素的指令。仍然会有多个(单独的)指令,就像所问的那样。请看,我在这里使用ng include和模板创建了一个替代解决方案,但我认为您的解决方案更优越,因为它不需要除指令之外的单独模板。所以,谢谢!
angular.module('myApp').directive('dynamicDirective', function($compile) {
return {
restrict: 'A',
link: function (scope, ele) {
//add a child div element that contains the directive specified in the type property
var itemEl = angular.element('<div>').attr(scope.item.type,'');
$compile(itemEl)(scope);
ele.append(itemEl);
}
};
});