2

We are facing multiple issues with select field's empty option.

My rendering code is as follows:

<select ng-switch-when="select" id="{{field.name}}" ng-model=data[field.name] >
<option ng-repeat="option in field.options" value="{{option.value}}">{{option.description}}
</select>

Here our UI is dynamically generated and options also populates dynamically using REST APIs. The Select field is bound to a data object that also populated using REST calls that might have blank value initially.

Issue

  1. It automatically adds a empty option where it is not required and disappear after selecting any non-empty option.
  2. Also it is showing following error for few select fields

TypeError: Cannot call method 'prop' of undefined at selectDirective.link.ngModelCtrl.$render (lib/angular/angular.js:20165:47) at Object.ngModelWatch (lib/angular/angular.js:16734:14) at Scope.$get.Scope.$digest (lib/angular/angular.js:11800:40) at Scope.$get.Scope.$apply (lib/angular/angular.js:12061:24) at done (lib/angular/angular.js:7843:45) at completeRequest (lib/angular/angular.js:8026:7) at XMLHttpRequest.xhr.onreadystatechange (lib/angular/angular.js:7982:11)

I have doubt that is use following code in angular

function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
ngModelCtrl.$render = function() {
var viewValue = ngModelCtrl.$viewValue;

  if (selectCtrl.hasOption(viewValue)) {
    if (unknownOption.parent()) unknownOption.remove();
    selectElement.val(viewValue);
    if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  } else {
    if (isUndefined(viewValue) && emptyOption) {
      selectElement.val('');
    } else {
      selectCtrl.renderUnknownOption(viewValue);
    }
  }

...

and it break at this line

if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy

because the empty option is provided by REST API at later stage and not available till initial rendering.

Please provide some suggestion for implementation and some alternate approach.

P.S : I can not use ng-option with select as it emit indexed values and I need actual values for some DOM manipulation.

1 Answers1

1

I would first read over how to do data-ng-options (http://docs.angularjs.org/api/ng.directive:select) because your select will cause you a bit of issues. Here's how you could move your code around:

<span data-ng-switch-when="select">
    <select id="{{field.name }}" data-ng-model="data[field.name]" data-ng-options="option.value as option.description for option in field.options></select>
</span>

Secondly, the reason that the blank option is selected is because data[field.name] is not set to a value that's present in option.value. You need to set it in your controller so the blank option goes away. You can see a similar question here: Why does AngularJS include an empty option in select?

Community
  • 1
  • 1
Mathew Berg
  • 28,625
  • 11
  • 69
  • 90