1. 程式人生 > >ionic開發——完整搜尋功能的實現方法

ionic開發——完整搜尋功能的實現方法

本文主要實現搜尋功能及清空搜尋內容的實現方法。

在angularjs中,我們的列表基本都是遍歷的一個物件陣列來顯示出來的,那麼我們的搜尋功能也就在這個基礎上來實現。

那就假設我們有一個事先顯示的物件陣列ItemArr1=[];

然後有一個輸入關鍵字搜尋後要顯示的另一個物件陣列ItemArr2=[];

HTML程式碼如下:

<ion-list>
        <ion-item class="item-input">      
                <span class="item-input-wrapper" style="margin-right:16px">
                        <i class="icon ion-ios-search placeholder-icon" ng-click="search()"></i>
                        <input id="search" type="search" placeholder="請輸出您想查詢的駕駛員姓名" ng-model="searchCont.key">
                        <i class="icon ion-close-circled placeholder-icon" style="vertical-align: middle;"
                            on-tap="clearSearch()" ng-if="searchCont.key.length"></i>
                 </span>
        </ion-item>
        <ion-item class="" ng-repeat="item in itemArr2"></ion-item>
</ion-list>
搜尋功能的JS程式碼如下:
        $scope.searchCont = {};//搜尋內容
        $scope.ItemArr2 = []; //搜尋後頁面遍歷顯示的陣列
        $scope.search = function(){
            $scope.ItemArr2 = []; //每次搜尋先清空陣列內容
            var searchValue = document.getElementById('search').value;
            for(var i=0;i<$scope.ItemArr1.length;i++){
                var num = i;
                for(var j=0;j<$scope.ItemArr1[num].name.length;j++){
                    var Name1 = $scope.ItemArr1[num].name.charAt(j);
                    for(var k=0;k<searchValue.length;k++){
                        var Name2 = searchValue.charAt(k);
                        if(Name1 == Name2){
                            if($scope.ItemArr2.indexOf($scope.ItemArr1[num])<0){
                                $scope.ItemArr2.push($scope.ItemArr1[num]); //如果有相同的字,切不在陣列內,加入陣列。
                            }
                        }
                    }
                }
            }
            if($scope.ItemArr2 == ''){
                alert('未找到匹配的駕駛員');
            }
        }

清空搜尋內容的JS程式碼:
        $scope.clearSearch = function(){
            $scope.searchCont = {};
            $scope.ItemArr2 = [];
        }
注:在label中的input不能嵌入按鈕,因為ionic對於label中的tap事件會進行重定向到input上。解決方案是將label替換成span或div。如下面的搜尋框,注意ng-model需要是一個物件才能置空,變數不行。

搜尋功能呼叫鍵盤搜尋鍵的實現方法可以看另一篇文章:  ionic開發——呼叫鍵盤搜尋功能實現方法

地址:http://blog.csdn.net/yu17310133443/article/details/52595392點選開啟連結