gerb0n
gerb0n

Reputation: 440

Angular Material autocomplete no data or not-found-message

My md-autocomplete doesn't show data and the md-not-found data at the same time.

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 shows the data but doesn't show the 'not-found-message'.
Attempt2 does show the 'not-found-message' but won't show data.

I wrapped it inside a promise.
How can I get them both to work at the same time?

Upvotes: 0

Views: 1441

Answers (1)

gerb0n
gerb0n

Reputation: 440

Turns out md-autocomplete does not do the 'search work' for you. You need to implement the search-logic and return the found items.

I made my search-logic aka filter generic so you don't have to make tons of search-logics.

    $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);
        };
    }

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

Upvotes: 0

Related Questions