【发布时间】:2015-05-19 11:40:03
【问题描述】:
角度 1.* ng-repeat 是否适用于 Set 和 Map 新对象?
有没有计划整合它?
【问题讨论】:
-
你有没有试过惨败?
-
我猜你说的是 Angular 1.3?
标签: javascript angularjs ecmascript-6
角度 1.* ng-repeat 是否适用于 Set 和 Map 新对象?
有没有计划整合它?
【问题讨论】:
标签: javascript angularjs ecmascript-6
Angular 在内部使用 for..in 运算符来遍历非数组对象。 Proof-link to the sources。 Map 和 Set 不能通过这种方式迭代,应该通过for..of 进行迭代。所以你不能在没有任何额外转换的情况下将此集合用于ng-repeat。
即将推出的 Angular 2 支持 ES6 功能,并且它也有 for..of 语法重复。详情请见angular 2 docs。
【讨论】:
我尝试在 Angular 2 中将 Map 绑定到 ng-repeat。即使使用 *ngFor="let item of items",它也不起作用。相反,这为我解决了问题:
/*
* Extension of the ES6 map, which also supports binding to it's array of values
*/
class BindableMap extends Map {
constructor(...args) {
super(...args);
this.bindableValues = [];
}
updateBindableValues() {
// Clear the array without creating a new one.
this.bindableValues.length = 0;
// Push all the new values
this.bindableValues.push(...Array.from(super.values()));
}
clear(...args) {
super.clear(...args);
this.updateBindableValues();
}
set(...args) {
super.set(...args);
this.updateBindableValues();
}
delete(...args) {
super.delete(...args);
this.updateBindableValues();
}
}
这样你也可以在 Angular 1.x 中使用ng-repeat="value in map.bindableValues"。
请注意,这不是最有效的解决方案,因为每次更改地图时都会重新创建可绑定值。就我的目的而言,这已经足够了。此外,如果您愿意,您还可以扩展 BindableMap 以绑定到键或键值对。
【讨论】: