Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 662
codevinsky Avatar asked Nov 27 '13 16:11

codevinsky


2 Answers

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 Example (in coffeescript): http://plnkr.co/edit/zIs0W7AdYnHnuV21UbwK

Plunker Example (in javascript): http://plnkr.co/edit/6VNJ8GUWK50etjUAFfey

like image 62
codevinsky Avatar answered Nov 20 '22 00:11

codevinsky


You can also do it directly in the html.

<select   ng-model="number"
          ng-options="item.id as item.label for item in values">
          <option value="" disabled selected style="display: none;"> Default Number </option>
></select>
like image 20
Joffrey Outtier Avatar answered Nov 20 '22 00:11

Joffrey Outtier