material icon indicating copy to clipboard operation
material copied to clipboard

autocomplete: require selection of option

Open shak18 opened this issue 11 years ago • 53 comments

can we configure in some way that the user is forced to select an option of our current set and dont leave garbage text in the input?

for example : lets asume i got the options (apple, banana, orange), if i type "ban" the autocomplete will sugest banana as a choice but if the user leaves the field he can just leave the incomplete text and dont set any valid option to the model,

is there anyway yo force a selection of a valid option (text or object)

shak18 avatar Apr 22 '15 16:04 shak18

+1

anderson-arlen avatar Apr 25 '15 20:04 anderson-arlen

Hmmm, some people (for example me) want completely different behaviour. I want to be able to make md-selected-item property md-search-text expression. So I can choose an item from the list or (if there is no match) write arbitrary text in the input field.

smashercosmo avatar Jun 15 '15 14:06 smashercosmo

@smashercosmo what you want does not exclude the other request. For example if you have a list of states, you want to force the users to select one of them, not create a new one or leave it as garbage. +1

SAnDAnGE avatar Jun 27 '15 09:06 SAnDAnGE

There definitely seems to be a use case for ensuring that users can only select from the list of existing items, particularly in cases where there may be a value different to the text. +1

oli107 avatar Jul 09 '15 14:07 oli107

I'm looking for the same functionality from autocomplete.

Another useful option might be that instead of forcing the selection of a unique match, the input should revert to the contents it had prior to the user typing anything. This will need to be implemented anyway for cases where there is no unique match from what has been typed, so it would be nice to have it as an alternative even if there is a unique match.

mrichar1 avatar Jul 29 '15 09:07 mrichar1

+1

ghost avatar Aug 04 '15 20:08 ghost

+1

jahanzebk avatar Aug 27 '15 21:08 jahanzebk

+1

zzo avatar Sep 04 '15 22:09 zzo

+1

nipuna-perera avatar Sep 30 '15 21:09 nipuna-perera

+1

MadMub avatar Oct 07 '15 20:10 MadMub

+1 Does anyone have a usable workaround for now?

stavro avatar Oct 08 '15 23:10 stavro

I don't have anything good unfortunately - on blur from the input field I check the value in the field - if it's not an 'allowed' value I make the input box empty. Since the field is marked as 'required' the normal form error handling now kicks in and displays the error that the field is required

zzo avatar Oct 08 '15 23:10 zzo

+1

maxime-menard avatar Oct 09 '15 12:10 maxime-menard

My workarround so far is this directive (apllied directly on the md-autocomplete element):

.directive('mdAutocompleteRequired',  function ($timeout) {
            return {
                restrict: 'A',
                require: '^form',
                link: function(scope, element, attr, ctrl) {
                    $timeout(function() {
                        var realModel,
                            elemCtrl = ctrl[attr.mdInputName],
                            realValidation = function (model) {
                                elemCtrl.$setValidity('selectedItem', !! realModel);
                                return model;
                            };
                        if ( !! attr.mdSelectedItem && !! attr.mdInputName) {
                            scope.$watchCollection(attr.mdSelectedItem, function (obj) {
                                realModel = obj;
                                realValidation()
                            });
                            elemCtrl.$parsers.push(realValidation);
                        }
                    })
                }
            }
        })

how to use:

<md-autocomplete md-input-name="field" md-selected-item="item" md-autocomplete-required ...></md-autocomplete>

this will add a custom validation to the inner input of the autocomplete named 'selectedItem' now you can use something like this:

<div ng-message="selectedItem">Invalid option selected</div>

or check the validity of the form

if( !! $scope.myform.$valid) ...

note: the autocomplete should be part of a form and the mdInputName attribute is required

shak18 avatar Oct 09 '15 20:10 shak18

If you want to mark the input field as invalid if the user does not select a md-autocomplete option this is easily achievable with a custom validator,

angular.module('demo').directive('forceSelect', ['$mdUtil', forceSelect]);

function forceSelect($mdUtil) {

  function postLink(scope, element, attrs, autoComplete) {
    let isSelected = (item) => {
      return autoComplete.matches.indexOf(item) !== -1;
    };

    $mdUtil.nextTick(() => {
      let ngModel = element.find('input').controller('ngModel');

      autoComplete.registerSelectedItemWatcher((selectedItem) => {
        ngModel.$setValidity('forceSelect', isSelected(selectedItem));
      });

      ngModel.$viewChangeListeners.push(() => {
        $mdUtil.nextTick(() => {
          ngModel.$setValidity('forceSelect', isSelected(autoComplete.scope.selectedItem));
        });
      });
    });
  }

  return {
    link: postLink,
    require: 'mdAutocomplete',
    restrict: 'A'
  };
}

Usage,

<md-autocomplete ... force-select></md-autocomplete>

daniel-nagy avatar Oct 12 '15 22:10 daniel-nagy

@daniel-nagy Thanks for the solution. The only issue I see is that you see flickering of required red message because when you select value from suggestion list blur handler is triggered before selected item is initialized. Adding some timeout to handler function helps though.

v-korshun avatar Oct 30 '15 17:10 v-korshun

@daniel-nagy That's a great one! Thanks for the solution! Just one point: put the "scope.$apply" inside a timeout to avoid exceptions when a digest is running.

CabuxaMapache avatar Dec 21 '15 09:12 CabuxaMapache

@shak18 I tried your solution, It worked, but it is not showing any error message, it just make that input field line as red.

mimani avatar Dec 21 '15 10:12 mimani

Also is there some solution, if autocomplete is inside md-chips, this is not working.

mimani avatar Dec 21 '15 10:12 mimani

@daniel-nagy can you provide a working plunker for your solution, I tried it but I start to get some unusual errors like : "Failed to instantiate moduleÆ

mimani avatar Dec 21 '15 10:12 mimani