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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With