如何在ionic2中使用angular2进行切换时构建数组

时间:2017-08-08 08:34:52

标签: javascript arrays angular

我想在切换时建立一个对象数组

 var data = [ 
          { catId : Vegitarian,
           subcats :[
                    {
                      category : "potatoes",
                      rank : 23,
                      catId : "Vegitarian"
                    },
                    {
                     category : "tomatoes",
                     rank : 2,
                     catId : "Vegitarian"
                    }
                  ]
            },
            { catId : "Non-vegetarian",
              subcats :[
                        {
                         category : "appetizers",
                         rank : 3,
                         catId : "Non-vegetarian"
                        },
                        {
                         category : "nonveg-appitizers",
                         rank : 52,
                         catId : "Non-vegetarian"
                        }
                      ]
               }

        ]

我的HTML代码

<div *ngFor="let cats of data">
<ion-row >
 <ion-toggle [(ngModel)]="cats.checked" (ionChange)="checkCats()"></ion-toggle>
</ion-row>

<div *ngFor="let subCats of cats.subcats">
   <ion-toggle [(ngModel)]="subCat.checked" (ionChange)="checkCats()"></ion-toggle>
</div>

</div>

我的要求是当我切换cats.checked时,下面所有subcats也必须选择,当我取消选择cats.checked时,所有subCats也有取消选择到这里我的代码工作正常,但当我取消选择单subCats时,重新cats.checked必须取消选择,如果我再次选择猫然后关联所有subCats啊选择

这是我的密码

this.result=[];
      checkCats(catObj) {
    this.result = this.data.filter(cats => {
          if ((cats.checked == true) && (cats.subcats.length != 0)) {
            cats.subcats.filter(subCat => {
              subCat.checked = true
            })
            return cats
          } else if ((cats.checked == true) && (cats.subcats.length == 0)) {
            return cats
          } else if ((cats.checked == false) && (cats.subcats.length != 0)) {
             cats.subcats.filter(subCat => {
              subCat.checked = false
            }) 
          }
    })

    }

我得到的结果

即使我取消选择了potatoes

,我也会获得整个对象
[
  {
    "catId": "vegetarian",
    "subcats": [
      {
        "subCatId": "potatoes",
        "catId": "vegetarian",
        "rank ": 23,
        "checked": true
      },
      {
        "subCatId": "tomatoes",
        "rank ": 2,
        "catId": "vegetarian",
        "checked": true
      }
     ]
   }
 ]

0 个答案:

没有答案