0

I have an existing select tag with existing option tags, one marked "selected", for example:

<div class="form-group">
  <label class="control-label">Test</label>
  <select ng-model="vm.testNumber">
    <option>Choose...</option>
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3" selected>three</option>
  </select>
  <p class="help-block">{{vm.testNumber}}</p>
</div>

Angular is binding to the model correctly and spits out "3" in the help block when the page loads, but option 3 is not selected. It binds and shows 3 as selected if I use text for the value attributes on each option, but not when it's a numerical value. Instead it inserts an option at the top of the select list:

<option value="? number:3 ?"></option>

What am I doing wrong?

2 Answers 2

2

From Angular DOC

Note that the value of a select directive used without ngOptions is always a string. When the model needs to be bound to a non-string value, you must either explicitly convert it or use ngOptions to specify the set of options. This is because an option element can only be bound to string values at present.

If you change your code as like as below code snippet, you don't need to do any explicit string conversions.

 <select ng-model="vm.testNumber" ng-options="item.value as item.label for item in [{label: 'one', value: 1}, {label: 'two', value: 2}]">
    <option value="">Choose...</option>
  </select>
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, was a bit late last night, didn't catch that this example was replacing 'one' with 1, 'two' with 2 in the option text
@MichaelTranchida, updated the solution, hope it helps
Ok, that works as I'd expect. Thank you. Think I'll stick with the directive in my answer, that way I don't have to worry (as much) about magic strings in my code.
1

Turns out you need to add a directive to make this work correctly. @codeninja.sj's answer ends up replacing 'one' with 1, 'two' with 2, etc. In the documention, the last example has this directive, convert-to-number

angular.module('app').directive('convertToNumber', function () {
return {
    require: 'ngModel',
    link: function (scope, element, attrs, ngModel) {
        ngModel.$parsers.push(function (val) {
            return parseInt(val, 10);
        });
        ngModel.$formatters.push(function (val) {
            return '' + val;
        });
    }
};
});

None of the other examples in the documentation worked for me.

Update @codeninja.sj's updated answer does work, however, figure this directive will cut down on magic strings in my code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.