我想要一个用户可以清除所选值的md-select.例如,他们选择一个值,但决定他们想要清除他们的选择.
md-select的行为是选择选项中的第一个条目.我想让它回到没有选择的状态.
我想我可能需要一个自定义指令,所以我实现了一个简单的指令,它监听DELETE键的keydown.
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>
Run Code Online (Sandbox Code Playgroud)
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);
}
})
}
}
});
})();
Run Code Online (Sandbox Code Playgroud)
这是我的代码笔:
http://codepen.io/craigsh/pen/GorpVV
但它不起作用 - 当按下DELETE键时,选择第一个选项值.
我建议除状态列表外还使用"null"选项:
<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>
Run Code Online (Sandbox Code Playgroud)
所以工作片段(改编自你的)可以是:
http://codepen.io/beaver71/pen/LGxqjp
在Angular-material文档中,他们将md-select的值设置为undefined
$scope.clearValue = function() {
$scope.myModel = undefined;
};
Run Code Online (Sandbox Code Playgroud)
您也可以在他们的网站上查看它 https://material.angularjs.org/latest/demo/select 请参阅验证部分
| 归档时间: |
|
| 查看次数: |
16146 次 |
| 最近记录: |