【问题标题】:How to bind to the new Set and Map objects?如何绑定到新的 Set 和 Map 对象?
【发布时间】:2015-05-19 11:40:03
【问题描述】:

角度 1.* ng-repeat 是否适用于 SetMap 新对象?

有没有计划整合它?

【问题讨论】:

  • 你有没有试过惨败?
  • 我猜你说的是 Angular 1.3?

标签: javascript angularjs ecmascript-6


【解决方案1】:

Angular 在内部使用 for..in 运算符来遍历非数组对象。 Proof-link to the sourcesMapSet 不能通过这种方式迭代,应该通过for..of 进行迭代。所以你不能在没有任何额外转换的情况下将此集合用于ng-repeat

即将推出的 Angular 2 支持 ES6 功能,并且它也有 for..of 语法重复。详情请见angular 2 docs

【讨论】:

    【解决方案2】:

    我尝试在 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 以绑定到键或键值对。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      相关资源
      最近更新 更多