【问题标题】:Ionic Search Bar - Search result priority离子搜索栏 - 搜索结果优先级
【发布时间】:2019-05-21 16:42:52
【问题描述】:

我在数组中有一组项目

我们称之为fruitArray。

fruitArray = ['Orange', 'Banana', 'Pear', 'Tomato', 'Grape', 'Apple', 'Cherries', 'Cranberries', 'Raspberries', 'Strawberries', 'Watermelon'];

现在,我在 Ionic 中执行正常的搜索操作。

当我在搜索框中输入值“ap”时,过滤后的列表按以下顺序显示项目 -

Grape

苹果ple

这是正常的搜索。

就我而言,我希望我的列表更改显示列表的顺序。

苹果ple

Grape

我想先显示以我的filterValue 开头的数据项,然后显示以我的filterValue. 为子字符串的数据项

提前致谢。

【问题讨论】:

    标签: angular ionic-framework search ionic2


    【解决方案1】:

    这是一种方法:

    在您的 .html 中,添加搜索栏

    <ion-toolbar class="subtoolbarsearch">
        <ion-searchbar autocorrect="true" placeholder="Look for a fruit" [(ngModel)]="search" (ionInput)="getItems($event)"></ion-searchbar>
    </ion-toolbar>  
    

    在您的 .ts 中,使用 2 个变量,一个包含所有水果和搜索栏的 ngModel

    public fruits;
    public search: string = "";
    

    添加一个设置水果的函数

    getFruits(){
        this.fruits = ['Orange', 'Banana', 'Pear', 'Tomato', 'Grape', 'Apple'];
     }
    

    从你的构造函数调用 if 来初始化 fruits 类变量

    最终在搜索栏输入时触发的函数

    getItems(ev) {
    
        this.getFruits(); // Display all the fruits
    
        let val = ev.target.value; // Getting the input
    
        // If searchbar is empty, do nothing
        if (val && val.trim() != '') {
    
            // Remove unmatching fruits
            for (let i = 0; i < this.fruits.length; i++) {
              let pos1 = this.fruits[i].toLowerCase().indexOf(val.toLowerCase());
              if (pos1 == -1) {
                this.fruits.splice(i, 1); // If substring not found, we remove the fruit from displayFruits
                i--; // Do not forget to decrement i by one since we removed one element from the array
              }else if(pos1 == 0){
                // If substring is at the beginning of the fruit name, we remove the fruit from the array, and we add it at the beginning of it
                let fruit = this.fruits[i];
                this.fruits.splice(i,1);
                this.fruits.unshift(fruit);
              }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 2013-11-28
      • 1970-01-01
      • 2023-04-04
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      相关资源
      最近更新 更多