AngularJS指令:如何在ng-repeat中动态更改元素html

AngularJS directives: How do I dynamically change the element html in an ng-repeat?

本文关键字:动态 元素 html ng-repeat 指令 AngularJS      更新时间:2023-09-26

我有一个角度指令,我正在对其应用ng重复。该指令的目的是将自身换成基于传递到原始指令的值的不同指令:

<content-type-directive type="item.type" ng-repeat="item in items"></content-type-directive>

成为

<type1-specific-directive></type1-specific-directive>
<type2-specific-directive></type2-specific-directive>
<type1-specific-directive></type1-specific-directive>
<type1-specific-directive></type1-specific-directive>
...

完整示例:http://jsfiddle.net/qPGZ8/6/

如果第二个指令的 html 可以在第一个指令的包装元素中呈现,这将很简单,但在这种情况下,我需要它来实际替换原始项目。

这与在指令中自定义模板有关

在 Misko 的回答中,他解释了使用 element.replaceWith() 来交换原始 html。当项目不在 ng 重复中时,这工作正常,但在 ng 重复中,它会破坏 ng-repeat 使用新元素更新自身的能力。

它与错误 https://github.com/angular/angular.js/issues/2151 有关。升级到最新版本1.2.0将修复它。

顺便说一句,按钮应该放在控制器的范围内。希望这是一个错字。

演示