Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disallow free text in md-autocomplete component of angular material?

How to disallow free text in md-autocomplete? I want the users to be only able to select from the list of items or add a ng-message based on some validation if the item is not selected from the list. Angular material md-autocomplete demo

like image 597
Navneet Avatar asked May 11 '16 09:05

Navneet


Video Answer


1 Answers

This is possible but needs some workarounds. You basically do the validation manually in selectedItemChange and searchTextChange.

function searchTextChange(text) {
  self.form.id.$error.stateMissing = true;
  $log.info('Text changed to ' + text);
}

function selectedItemChange(item) {
  $log.info(self.form.id);
  if (item === null) {
    $log.info('invalid');
  } else {
    $log.info('valid');
    delete self.form.id.$error.stateMissing;
    self.form.id.$validate();
  }
}

The error is set in the stateMissing property and then used in the ng-message markup. It is important to set a the form name so you can have a reference to the form in your controller.

<form name="ctrl.form" novalidate>
  <p>Use <code>md-autocomplete</code> to search for matches from local or remote data sources.</p>
    <md-autocomplete md-autoselect md-select-on-focus md-floating-label="Select a state" ng-disabled="ctrl.isDisabled" cache="ctrl.noCache" md-selected-item="ctrl.selectedItem" md-input-name="id" md-search-text-change="ctrl.searchTextChange(ctrl.searchText)" md-search-text="ctrl.searchText" md-items="item in ctrl.querySearch(ctrl.searchText)" md-item-text="item.display" md-min-length="0" md-selected-item-change="ctrl.selectedItemChange(ctrl.selectedItem)">
      <md-item-template>
        <span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.display}}</span>
      </md-item-template>
      <md-not-found>
        No states matching "{{ctrl.searchText}}" were found.
        <a ng-click="ctrl.newState(ctrl.searchText)">Create a new one!</a>
      </md-not-found>
      <div ng-messages="ctrl.form.id.$error">
        <div ng-message="stateMissing">You must select a state</div>
      </div>
    </md-autocomplete>

http://codepen.io/kuhnroyal/pen/eZXXVr

like image 178
kuhnroyal Avatar answered Nov 08 '22 17:11

kuhnroyal