根据下拉列表中选择的项目筛选JSON API数据

时间:2017-09-15 08:10:25

标签: javascript json angular typescript ionic2

美好的一天,我目前正在开发Ionic 2应用程序,而且我在下拉菜单上的所选项目上过滤数据库时遇到了困难。

这是我的代码:

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

我想要做的是,当我在省份下拉菜单中选择省份时,只有省内的城市才会显示在城市下拉菜单中。

enter image description here

我仍然不知道如何在我的代码中实现这种过滤。希望你们能帮助我。提前谢谢。

1 个答案:

答案 0 :(得分:1)

假设城市对象具有省名属性,您可以拦截离子选择的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.");
        });
}