2017-09-13 33 views
0

我使用md-autocomplete讓用戶在我的大學中搜索主題。AngularJS md-autocomplete返回所有可能的子字符串

問題是我的搜索功能,通過每個顯示值只搜索(從左到右)。

例如:如果我搜索「藝術與建築」,我會得到「找不到結果」,我不希望發生這種情況。

我想要「藝術與建築學」返回結果。

的對象是格式爲:

$scope.subjects = [ 
    { 
    value: 'AA', 
    display: 'AA - Arts and Architecture' 
    }, 
    { 
    value: 'AAAS', 
    display: 'AAAS - African/Afr Amer Studies' 
    }, 
    { 
    value: 'ABA', 
    display: 'ABA - Applied Behavior Analysis' 
    }, 
    { 
    value: 'ABE', 
    display: 'ABE - Ag and Biological Engineering' 
    } 
] 

這裏是我的搜索方法:

$scope.searchQuery = function(text) { 
    text = text.toUpperCase(); 
    var result = $scope.subjects.filter(function(item) { 
    return item.display.includes(text); 
    }); 
    return result; 
} 

這裏是我的html:

<md-autocomplete 
    md-selected-item="selectedItem" 
    md-search-text="searchText" 
    md-items="item in searchQuery(searchText)" 
    md-item-text="item.display" 
    md-min-length="0" 
    placeholder="Select a subject"> 
    <md-item-template> 
    <span md-highlight-text="searchText">{{item.display}}</span> 
    </md-item-template> 
    <md-not-found> 
    No matches found. 
    </md-not-found> 
</md-autocomplete> 

回答

1

問題

這是由於區分大小寫,即你實際上在做的相當於...

"Arts and Architecture".includes("ARTS AND ARCHITECTURE"); // false 

.. 。因爲includes區分大小寫,它將返回false。它只是發生在你的字符串的開始工作,因爲所有的字母都大寫和輸入也爲大寫:

"AA".includes("AA"); // true (fluke!) 

解決方案

如果您item.displaytext大寫它應該工作:

$scope.searchQuery = function(text) { 
    var result = $scope.subjects.filter(function(item) { 
    return item.display.toUpperCase().includes(text.toUpperCase()); 
    }); 
    return result; 
} 
+1

希望我能接受這兩次 - 謝謝! – User11

+0

沒問題,你總是可以upvote反而!高興它幫助。 –

+2

沒有足夠的代表 – User11

0

按照文件JS方法str.includes(searchString[, position])狀態:

參數:位置 - >可選。搜索字符串中搜索 for searchString的位置(默認爲0)。

所以你的代碼是從指數0

如何開始使用有關的indexOf呢?改變這一行:return item.display.includes(text);

return item.display.indexOf(text) !== -1;

+0

謝謝,但沒有奏效。任何其他建議? – User11

0

「includes」函數只檢查目標字符串中是否存在搜索字符串。爲了使md-autocomplete正常工作,您需要匹配數組中包含搜索文本或部分搜索文本的對象。修改您的代碼到:

$scope.searchQuery = function(text) { 
    var result = $scope.subjects.filter(function(item) { 
     if (item.display.toUpperCase().indexOf(text.toUpperCase()) >-1) 
      return item; 
}); 
    return result; 
} 
相關問題