2017-09-15 70 views
0

美好的一天,我目前正在研究Ionic 2應用程序,並且我很難在下拉菜單上過濾所選項目上的數據庫。根據在下拉列表中選擇的項目過濾JSON API數據

這裏是我的代碼:

TS文件:

this.http.get('http://sample.com/xxx/api.php/address_province?transform=1') 
.map(res => res.json()) 
.subscribe(data => { 
    this.province = data.address_province; 
    console.log(this.province); 
}, (err) => { 
    console.log("Something went wrong."); 
}); 


this.http.get('http://sample.com/xxx/api.php/address_city?transform=1') 
.map(res => res.json()) 
.subscribe(data => { 
    this.city = data.address_city; 
    console.log(this.city); 
}, (err) => { 
    console.log("Something went wrong."); 
}); 

模板

 <ion-item> 
      <ion-label>Province</ion-label> 
      <ion-select [(ngModel)]="registerprovince" > 
      <ion-option *ngFor="let prov of province" value="{{prov.province_description}}">{{prov.province_description}}</ion-option> 
      </ion-select> 
     </ion-item> 

     <ion-item> 
      <ion-label>City</ion-label> 
      <ion-select [(ngModel)]="registercity" > 
      <ion-option *ngFor="let cities of city" value="{{cities.city_description}}">{{cities.city_description}}</ion-option> 
      </ion-select> 
     </ion-item> 

enter image description here

我想要做的是,當我選擇了一個省省下拉菜單,只有省下的城市纔會顯示在前面y下拉菜單。

enter image description here

我仍然不知道我將如何實現這種過濾在我的代碼。希望你們能幫助我。先謝謝你。

回答

1

讓假設城市對象有provinceName屬性,你可以截取的離子選擇ionChange事件,做城市濾波省時的變化:

<ion-item> 
    <ion-label>Province</ion-label> 
    <ion-select [(ngModel)]="registerprovince" (ionChange)="onProvinceChange($event)> 
     <ion-option *ngFor="let prov of province" value="{{prov.province_description}}">{{prov.province_description}}</ion-option> 
    </ion-select> 
</ion-item> 

<ion-item> 
    <ion-label>City</ion-label> 
    <ion-select [(ngModel)]="registercity"> 
     <ion-option *ngFor="let city of filteredCities" value="{{city.city_description}}">{{city.city_description}}</ion-option> 
    </ion-select> 
</ion-item> 

// In your component's class: 

filteredCities = []; 

onProvinceChange(selectedProvince: any) { 
    console.log('Selected', selectedProvince); 
    this.filteredCities = this.cities.filter(city => city.provinceName === selectedProvince.province_description); 
} 

ngOnInit() { 
    this.http.get('http://sample.com/xxx/api.php/address_city?transform=1') 
     .map(res => res.json()) 
     .subscribe(data => { 
      this.cities = data.address_city; 
      this.filteredCities = data.address_city; 
     }, (err) => { 
      console.log("Something went wrong."); 
     }); 
} 
相關問題