AngularJS – Issues binding your model to select list when types don’t match

An issue I’ve run into a few times when binding a model’s foreign key field to a drop down is that my drop down list will have select items where the name and value are both strings, and the model will have a foreign key which is an int that I’m trying to bind to that select list. Since my model’s field is an int, and the values of the select list are strings, they fail to bind as expected.

A very simple fix is to multiply your values in your select list by 1 which converts the string to an int, and then the model binds as expected.

Since a code sample is worth a 1000 words, look at this situation. I have a ‘task’ model for the page. The task’s TaskTypeId is an int.

task.TaskTypeId = int (=23)

I have a list of taskTypes in a selectList. The Id value here is a number but it is a string

taskType.Id = string (=”23″)

This is not working:

<label>Type:</label> 
    <select
    ng-model="task.TaskTypeId"
    ng-options="taskType.Id as taskType.Name for taskType in taskTypes" ></select>

This does work:

<label>Type:</label> 
    <select
    ng-model="task.TaskTypeId"
    ng-options="taskType.Id*1 as taskType.Name for taskType in taskTypes" ></select>

I’m still looking for the best practice, but this is a simple working solution.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s