如何添加一个不可选择的,可定制的占位符来选择框 [英] How do I add an unselectable and customizable placeholder to a select box
问题描述
我有一个pretty大型的应用程序,有许多下拉菜单。我不希望有修改我的数据添加一个空白选项,我不希望占位符是可选择的。什么是最好的方法呢?
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?
推荐答案
我们可以用角强大的指令系统来扩展基本的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屋!