Guide to assigning a value to a model in AngularJS by utilizing a select input with an array of objects

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!

Answer №1

It is recommended to use author.id as author.name in your ng-options like the examples below:

<div ng-app="app">
  <div ng-controller="testController">
    <select ng-options="author.id as author.name for author in authors track by author.id" ng-model="bookModel.author"></select>
    <pre>{{bookModel.author | json}}</pre>
  </div>
</div>

Alternatively, if you prefer the author's name:

<div ng-app="app">
  <div ng-controller="testController">
    <select ng-options="author.name as author.name for author in authors track by author.id" ng-model="bookModel.author"></select>
    <pre>{{bookModel.author | json}}</pre>
  </div>
</div>

UPDATE 1

Link to your updated fiddle

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble getting the jquery tabify plugin to work properly

I've put in a lot of effort and double-checked everything, but for some reason this tabify function just won't work. I have gone through my code 100 times but still can't seem to pinpoint the error. Here is the code I am working with: <! ...

Tips for creating a unique scroll page arrow button with adjustable thickness?

Seeking guidance on how to adjust the thickness of the arrow used as a scroll button on my website. I am aiming for a similar look to the arrow on this particular website: example of arrow To view my code, please visit: Codepen .next { position:absolut ...

I keep encountering an error that says "ReferenceError: localStorage is not defined" even though I have already included the "use

I have a unique app/components/organisms/Cookies.tsx modal window component that I integrate into my app/page.tsx. Despite including the 'use client' directive at the beginning of the component, I consistently encounter this error: ReferenceErr ...

Issue with Navigation Scrolling Feature on Wordpress

I am in the process of implementing a 'scroll-nav' for my website. To achieve this, I decided to separate the Navigation into two sections and incorporate some jQuery: <nav class="main-nav clearfix"> <?php wp_nav_menu(array('th ...

Custom providers do not override Angular UrlResolver

In my Angular application, I am trying to implement a custom UrlResolver provider to incorporate cache breaking logic. I came across this question on Stack Overflow: . Unfortunately, it seems that overriding the default compiler UrlResolver using a provid ...

Issue with retrieving Combobox value within AngularJS ng-repeat generated table using ng-model

Here is my code that I need help with: <thead> <tr> <th>Id Detalle_Venta</th> <th>Id Producto</th> <th>Producto </th> <th>Cantidad </th> <th>Direccion </th> ...

What seems to be the issue with this Discord.js kick command code? It's not

Okay, so I'm in the process of creating a kick command for my Discord bot. The issue I'm encountering is that when no reason is specified or if a user is not mentioned to be kicked, the bot responds correctly but does not actually kick the user. ...

Scrollable content with sticky positioning using CSS3 and JavaScript

I successfully implemented a sidebar using the position: sticky property and it is functioning perfectly. To identify colors in the following text, refer to the script below. When scrolling, the black area remains fixed while the green area sticks to its ...

Can anyone help me with integrating a search functionality inside a select tag?

I am working on a select dropdown and want to add a search box to easily filter through the available options. I know this can be done using the chosen library, but I prefer to implement it using plain JavaScript or jQuery. Does anyone have suggestions on ...

How to include subdirectories in a TypeScript npm module

I am in the process of developing a package for npm and I would like it to be imported in the following manner: import myPackage from 'my-package'; import { subFunction1, subFunction2 } from 'my-package/subfunctions'; Upon trying to u ...

A Firefox Browser View of a Next.js and Tailwind Website magnified for closer inspection

After creating a website using Next.js and Tailwind CSS, I noticed that the site is appearing zoomed in when viewed in Firefox. However, it looks fine in all other browsers. When I adjust the screen to 80%, the website displays correctly in Firefox. What ...

Utilizing ACE editor in conjunction with Angular for dividing the input by new lines

I have successfully integrated the ACE code editor into my application using the ace-ui directive with angular. Overall, it has been working well, but there is one issue I am facing. I want the code written in the editor to be stored as an array of string ...

Vows: proceed to the subsequent error handling process

Can you explain how to properly call the next error function using promise chaining? I initially believed that placing a return statement within the error function would automatically trigger the next error function. //This code is executed in a contr ...

The Ajax validation form mistakenly redirects the echoes to a different page instead of the intended page for displaying the output

I am currently working on creating an ajax-form to validate the client-side server of my sign-up form. My goal is to have error messages displayed on the same page where they are triggered, without loading a separate page. Below is the code from my (sign ...

Utilizing v-if and splice on users to select items from v-model

After following a tutorial, I have the code snippet below that I would like to enhance: <div style="margin-top: 10px;"> v-for="task in taskItems" :key="task.id" <q-icon :name="task.icon"/> <div ...

What error am I making in the Date calculator for the select box using Javascript/jQuery?

$(.dateselboxes) .change( function(){ var y; y=$("#year").val(); var m; m=$("#month").val(); var d; // check for leap year var isLeapYear; if(y%4==0) { if(y%100==0) { if(y%400==0) {isLeapYear=true;} else {isLeapYear=false;} } ...

We were unable to locate the module '@reactflow/core' or its associated type declarations

After forking reactflow, I attempted to make some modifications but encountered a type error even without making any changes. My next step was to try "pnpm i @types/reactflow," but it did not resolve the issue. ...

Leveraging two AJAX requests within a single function

I am working on creating an ajax function to post data that I've retrieved using another ajax function. While I have figured out how to use a callback function, I am struggling with passing the data from one function to the other. Here is what I have ...

`Inconsistent form variable behavior persists despite multiple ajax requests`

I'm in the process of creating a basic email submission form and I've decided to use ajax for it. The issue I'm encountering is that after successfully submitting the form once, any subsequent modifications made to the text within the form a ...

No data returned from Ajax GET request

Utilizing Ajax with JavaScript, I am processing data on a PHP page using the GET method. Is it possible to send data from the PHP page when the GET query is empty? My goal is to have a live search feature that filters results based on user input. When a us ...