I'm wanting to have an md-select that the user can clear the selected value. E.g. they select a value but decide they want to clear their selection.
The behavior of md-select is to select the first entry in the options. I'd like to make it return to the state where no selection was made.
I'm imagining I probably need a custom directive for this, so I've implemented a simple directive which listens to the keydown for the DELETE key.
HTML:
<div ng-controller="AppCtrl as ctrl" class="md-padding selectdemoBasicUsage" ng-cloak="" ng-app="MyApp">
<div>
<h1 class="md-title">Select a state</h1>
<span>I want the DELETE key to be able to clear the selected state.</span>
<div layout="row">
<md-input-container>
<label>State</label>
<md-select ng-model="ctrl.userState" select-clear>
<md-option ng-repeat="state in ctrl.states" value="{{state.abbrev}}">
{{state.abbrev}}
</md-option>
</md-select>
</md-input-container>
</div>
</div>
</div>
JS:
(function () {
'use strict';
angular
.module('MyApp',['ngMaterial', 'ngMessages'])
.controller('AppCtrl', function() {
this.userState = '';
this.states = ('AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS ' +
'MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI ' +
'WY').split(' ').map(function (state) { return { abbrev: state }; });
})
.directive('selectClear', function() {
return {
restrict: 'A',
require: 'ngModel',
link : function(scope, iElement, iAttrs, ngModelCtrl) {
iElement.bind('keydown', function(event) {
if (event.keyCode === 46) {
ngModelCtrl.$setViewValue('', event);
}
})
}
}
});
})();
Here's my code pen:
http://codepen.io/craigsh/pen/GorpVV
But it doesn't work - when the DELETE key is pressed the first options value is selected.
I suggest to use a "null" option in addition to the states list:
<md-select ng-model="ctrl.userState" select-clear>
<md-option value="{{null}}">
-- select a state --
</md-option>
<md-option ng-repeat="state in ctrl.states" value="{{state.abbrev}}">
{{state.abbrev}}
</md-option>
</md-select>
so the working snippet (adapted from yours) could be:
http://codepen.io/beaver71/pen/LGxqjp
In the Angular-material docs they set the value of your md-select to undefined
$scope.clearValue = function() {
$scope.myModel = undefined;
};
You can check it too in their site https://material.angularjs.org/latest/demo/select see the Validations section
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