2

I have (a seemingly common) problem with empty option values an angular model viewed using a select using ng-options.

$scope.groupTypeOptions = [
    { group: 'g1', name: '---', value: null }, 
    { group: 'g2', name: 'Feature', value: 'feature' }, 
    { group: 'g2', name: 'Bug', value: 'bug' }, 
    { group: 'g2', name: 'Enhancement', value: 'enhancement' }
];

<select ng-model='form.groupType' required ng-options='option.value as option.name group by option.group for option in groupTypeOptions'></select>

A fiddle can be seen here: http://jsfiddle.net/v6z3zh49/

My goal is to, from a predefined model, show a grouped select with the selected item representing null (or empty string). However, when selecting a value and I always end up with an extra, empty, option element being added. See fiddle above.

I have looked at similar questions, for example here and here, but cannot find a solution.

Any tips?

Community
  • 1
  • 1
Victor
  • 3,999
  • 3
  • 24
  • 27

1 Answers1

1

Try:

$scope.groupTypeOptions = [
        { group: 'g1', name: '---', value: undefined }, 
    { group: 'g2', name: 'Feature', value: 'feature' }, 
    { group: 'g2', name: 'Bug', value: 'bug' }, 
    { group: 'g2', name: 'Enhancement', value: 'enhancement' }
    ];

It happens because in javascript null !== undefined.

Hope, it will help.

Demo: http://jsfiddle.net/ababashka/skk4uj1y/

ababashka
  • 2,101
  • 1
  • 14
  • 15
  • THANK YOU! That really bugged me, very nice catch! Additional question: why doesn't the "track by" expression seem to work? See updated example at http://jsfiddle.net/ynb09mdb/ The manual at https://docs.angularjs.org/api/ng/directive/select seems to indicate that the "select as label group by group for value in array track by trackexpr" syntax should work? – Victor Sep 26 '14 at 22:07
  • 1
    @Victor: Hi, you are welcome with my answer) About your another question about `track by` - the thing is, you just can't combine `value as label for collection` with `track by`. You can see an angular issue https://github.com/angular/angular.js/issues/6564 and explanation in the comments from `janv` on 8'th of Aug. – ababashka Sep 29 '14 at 07:27