如何向选择框添加不可选择且可自定义的占位符 [英] How do I add an unselectable and customizable placeholder to a select box
问题描述
我有一个非常大的应用程序,它有很多下拉菜单.我不想修改我的数据来添加一个空白选项,我不希望占位符是可选的.最好的方法是什么?
I've got a pretty large app that has many dropdowns. I don't want to have to modify my data to add a blank option and I don't want the placeholder to be selectable. What's the best approach?
推荐答案
我们可以通过使用 angular 强大的指令系统来扩展基本 html 来轻松做到这一点.
We can do this easy by using angular's powerful directive system to extend basic html.
app.directive('select', function($interpolate) {
return {
restrict: 'E',
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
var defaultOptionTemplate;
scope.defaultOptionText = attrs.defaultOption || 'Select...';
defaultOptionTemplate = '<option value="" disabled selected style="display: none;">{{defaultOptionText}}</option>';
elem.prepend($interpolate(defaultOptionTemplate)(scope));
}
};
});
有了这个,我们现在可以做到以下几点:
With this, we can now do the following:
<select ng-model="number"
ng-options="item.id as item.label for item in values">
</select>
这将创建一个带有不可选择占位符的选择框,上面写着选择..."
This will create a select box with an unselectable placeholder that says "Select..."
如果我们想要一个自定义占位符,我们可以简单地这样做:
If we want a custom placeholder we can simply do this:
<select ng-model="dog"
ng-options="dog.id as dog.label for dog in dogs"
default-option="What's your favorite dog?">
</select>
这将创建一个带有不可选择占位符的选择框,上面写着你最喜欢的狗是什么?"
This will create a select box with an unselectable placeholder that says "What's your favorite dog?"
Plunker 示例(在 coffeescript 中):http://plnkr.co/edit/zIs0W7AdYnHnuV21UbwK
Plunker Example (in coffeescript): http://plnkr.co/edit/zIs0W7AdYnHnuV21UbwK
Plunker 示例(在 JavaScript 中):http://plnkr.co/edit/6VNJ8GUWK50etjUAFfey
Plunker Example (in javascript): http://plnkr.co/edit/6VNJ8GUWK50etjUAFfey
这篇关于如何向选择框添加不可选择且可自定义的占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!