ceckenrode ceckenrode - 6 months ago 23
AngularJS Question

ng-model is number, select box option values are strings

I have the following code

<select ng-disabled="currentQuestion.id" ng-change="loadTopics()" class="detail-subject-select browser-default" ng-model="currentQuestion.SubjectId">
<option disabled="disabled" value="any">Choose a Subject</option>
<option value="1">K8-English</option>
<option value="2">K8-Math</option>
</select>


The issue is that value 1 and 2 are strings. I need them to be numbers. Everything works fine when I select one on my page, but I need the select box to initialize with the value of (currentQuestion.SubjectId which is a number) when the page loads.

How can I get around this?

Answer

One way is to define your options as an array of objects in your controller like this:

$scope.options = [{ value: 1, name: 'K8-English' }, { value: 2, name: 'K8-Math' }];

And implement this in your HTML using ng-options like this:

<select ng-disabled="currentQuestion.id"
    ng-change="loadTopics()"
    class="detail-subject-select browser-default"
    ng-model="currentQuestion.SubjectId"
    ng-options="option.value as option.name for option in options">
        <option disabled="disabled" value="any">Choose a Subject</option>
</select>