0

I've been trying to resolve the issue from this SO question that has to do with temporary empty <select> options because ng-model doesn't match an option.

The solution to use the following line works perfectly, but only when I drop that HTML directly in:

<option style="display:none" value="">(select)</option>

I have a directive created to standardize the "(select)" text and create that empty option when needed:

empty-default-option.js

(function () {
    'use strict';

    function EmptyDefaultOptionDirective() {
        return {
            restrict: 'A',
            link: function (scope, element) {
                element.prepend('<option style="display:none" value="">(select)</option>');
            }
        };
    }

    angular.module('utils.empty-default-option', [])
        .directive('emptyDefaultOption', EmptyDefaultOptionDirective);
}());

This doesn't work when used in the HTML file:

context.html

<select class="form-control"
        ng-model="context.contextChoice"
        empty-default-option>
            <option ng-repeat="choice in context.choices_data | orderBy:'id'">{{choice.first_name}} {{choice.last_name}}</option>
</select>

(context.js sets contextChoice = "", so I don't think it's that. controllerAs: 'context', also.)

I still get a temporary blank empty option, which to me means my directive option wasn't seen. I feel like this has to do with link versus controller, perhaps, or timing of when things are scanned or checked, but I'm having trouble finding answers.

Thanks for reading!

Community
  • 1
  • 1
Ross Llewallyn
  • 66
  • 2
  • 11

1 Answers1

0

I had the right idea about the problem. A coworker pointed me towards this answer.

In the directive definition, the inserting of the <option> needs to happen earlier, so use compile: instead of link::

compile: function compile(tElement) {
    tElement.prepend('<option style="display:none" value="">(select)</option>');
}
Ross Llewallyn
  • 66
  • 2
  • 11