I'm new to AngularJS and I've encountered a challenge that requires an elegant solution.
My application receives a list from the server, which is used as the data source for the select
tag's options. Let's assume this list represents authors and looks like this:
[
{ id: 1, name: 'Mark Twain' },
{ id: 2, name: 'Jack London' },
{ id: 3, name: 'Ernest Hemingway' }
]
In addition, I have a book model which also comes from and is saved to the server. One of the properties of the book is the author, which the user selects from a dropdown in the form of a number corresponding to the author's ID. Here is an example of how the book model should be saved and fetched from the server:
{
id: 324,
title: 'Martin Eden',
author: 2
}
The book model is represented by Angular's $resource
, so saving the book model involves calling its save method.
To implement this logic, I attempted to use ng-options
with a select
element like this:
<select ng-options="author.id as author.name for author in authors track by author.id" ng-model="bookModel.author"></select>
However, the issue with this approach is that selecting an author sets the value of the author
property to the whole object ({ id: 2, name: 'Jack London' }) instead of just the author's ID.
I created a Fiddle to demonstrate the problem. Try selecting different values from the drop-down menu, and you'll see the updated value of bookModel.author
below. I require this value to be the author's ID integer, not the object itself. If it's not possible, I would need to manipulate the data every time the book model is retrieved or saved. Is there a better way to achieve this, perhaps using ng-options
?
I also tried another approach:
<select ng-model="bookModel.author">
<option ng-repeat="author in authors" value="{{author.id}}">{{author.name}}</option>
</select>
This method gets closer to the desired outcome, but the value of bookModel.author
ends up being a string rather than an integer.
I am aware that I can set transformRequest
and transformResponse
functions for the book $resource to handle data transformation, but I wonder if there is a more effective way to address this issue.
Any assistance would be greatly appreciated!