Angular Material自动完成无数据或未找到消息

时间:2016-09-12 13:37:57

标签: angularjs angular-material md-autocomplete

我的md-autocomplete不会同时显示数据和md-not-found数据。

angular.module('BlankApp').controller('ctrl', function($scope, $q){
    $scope.items = [{name: 'item1', id: 1}, {name: 'item2', id: 2}, {name: 'item3', id: 3}];

    $scope.promisedItems = function(){
        var deferred = $q.defer();
        deferred.resolve(items);
        return deferred.promise;
    }
});

<md-autocomplete md-selected-item="selectedItem2" md-search-text="searchText2" md-items="item in promisedItems()" md-item-text="item.name" md-min-length="0" placeholder="items">
    <md-item-template>
        <span md-highlight-text="searchText2" md-highlight-flags="^i">{{item.name}}</span>
    </md-item-template>
    <md-not-found>
        No states matching "{{searchText2}}" were found.
    </md-not-found>
</md-autocomplete>

Check the following codepen

Attempt1显示数据,但未显示“not-found-message”。
Attempt2确实显示'not-found-message'但不显示数据。

我把它包裹在一个承诺里面。
我怎样才能让它们同时工作?

1 个答案:

答案 0 :(得分:0)

原来md-autocomplete不会为你做'搜索工作'。 您需要实现搜索逻辑并返回找到的项目。

我将搜索逻辑称为过滤器通用,因此您不必进行大量的搜索逻辑。

    $scope.searchCollection = function (searchString, collection, propertyName) {
        var deferred = $q.defer();
        var result = searchString ? collection.filter(createFilterFor(searchString, propertyName)) : collection;
        deferred.resolve(result);
        return deferred.promise;
    }

    function createFilterFor(searchString, propertyName) {
        var lowercaseQuery = angular.lowercase(searchString);
        return function filterFn(item) {
            return (angular.lowercase(item[propertyName]).indexOf(lowercaseQuery) === 0);
        };
    }

用法md-items="item in searchCollection(searchText, myCollection, 'propertyNameToSearchIn')"