How do I add an unselectable and customizable placeholder to a select box

后端 未结 2 813
醉话见心
醉话见心 2020-12-29 06:52

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\

2条回答
  •  没有蜡笔的小新
    2020-12-29 07:39

    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 = '';
          elem.prepend($interpolate(defaultOptionTemplate)(scope));
        }
      };
    });
    

    With this, we can now do the following:

    
    

    This will create a select box with an unselectable placeholder that says "Select..."

    If we want a custom placeholder we can simply do this:

    
    

    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

提交回复
热议问题