material icon indicating copy to clipboard operation
material copied to clipboard

Removing an item from md-autocomplete once selected

Open jvgeee opened this issue 10 years ago • 2 comments

I'm using md-autocomplete within md-chips, as per the docs (using 1.0.1)

It's working fine, but I'd like to update the autocomplete suggestions to omit things that have already been selected.

Here's my view (forgive the Jade!)

  md-chips(ng-model="banned", md-autocomplete-snap, md-transform-chip="transformChip($chip)", md-require-match="true", md-on-add="addChip($chip)", md-on-remove="removeChip($chip)")
     md-autocomplete(md-selected-item="selectedItem", md-search-text="searchText", md-items="item in querySearch(searchText)", md-item-text="item.name", placeholder="Search for a domain", md-autoselect="true")
        span(md-highlight-text="searchText")
           {{item.name}}

     md-chip-template
        span {{$chip.name}}

And some relevant JS, I'm using autocomplete on the $scope.domains array:

$scope.querySearch = function (query) {
    console.log($scope.domains);
  var results = query ? $scope.domains.filter(createFilterFor(query)) : [];
  return results;
}


function createFilterFor(query) {
  var lowercaseQuery = angular.lowercase(query);
  return function filterFn(dom) {
    return (dom.name.indexOf(lowercaseQuery) === 0);
  };
}

$scope.addChip = function($chip){
    var dom = $chip.name;

    // Remove domain from $scope.domains
    $scope.domains = $scope.domains.filter(function(e){
        console.log(e.name, dom, e.name!==dom);
        return e.name !== dom
    })

    console.log($scope.domains);

}

I can see that after selecting a chip, $scope.domains is successfully updated. But when I try to type in the autocomplete - the suggestion is still there!

This also completely breaks the autocomplete (suggestions only show for a few letters, then disappear as you type more even if they match).

Has anyone done this successfully? Is md-autocomplete caching the data model or something?

jvgeee avatar Jan 13 '16 23:01 jvgeee

Look at my code from https://github.com/angular/material/issues/4673

There is still an issue about caching when the list is empty and min-length=0, but it still works as you asked.

antoinebrault avatar Jan 29 '16 17:01 antoinebrault

Use the property of md-autocomplete md-no-cache = true.

Update your method called from md-items to avoid itens already selected like this:

    function queryGroupSearch (query, model) {

        var results = query ? GroupService.groupsByUser.filter(createGroupFilterFor(query)) : GroupService.groupsByUser;

        for (var i = 0; i < model.length; i++) {

            for (var i2 = 0; i2 < results.length; i2++) {

                if (results[i2].name.toLowerCase() == model[i].name.toLowerCase()) {

                    results.splice(i2, 1);

                }

            }

        }

        return results;
    }

claudiozanin avatar Mar 04 '16 13:03 claudiozanin