gpt4 book ai didi

javascript - 在 AngularJS 中使用元数据动态插入指令?

转载 作者:行者123 更新时间:2023-12-02 17:38:32 26 4
gpt4 key购买 nike

我想定义元数据,它将根据“类型”值动态使用正确的指令:

$scope.items = [
{
type: 'directive-one',
value: 'One'
},{
type: 'directive-two',
value: 'Two'
},{
type: 'directive-three',
value: 'Three'
}
];

然后

<li ng-repeat="item in items" {{type}}>
{{value}}
</li>

我创建了一个 jsfiddle here 。到目前为止我还没有成功

这可能吗?我该如何实现这个目标?

最佳答案

这是解决问题的另一种方法:

使用 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>

See jsfiddle

但是,如果您确实需要在元数据中定义指令,则可以添加一个指令,该指令将使用适当的指令生成 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);
}
};
});

See jsfiddle

关于javascript - 在 AngularJS 中使用元数据动态插入指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22415905/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com