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

Experience the power of module federation in Next JS without using the @module-federation/nextjs-mf package

Currently transitioning from Java to JavaScript, I am working on a Next.js project. I have a requirement to share the client component from this Next.js project with another project built on React. Upon discovering module federation, I successfully created ...

Updating data for a heatmap in Angular-Leaflet

My goal is to display a dynamic heatmap using the Angular-Leaflet directive. I have written the following code: getData().then(function (data) { $scope.heat.index = 0; $scope.heat.data = data; $scope.layers.overlays.heat = { name: "Hea ...

Looking for assistance with deleting a child element in an XML file using PHP

I need help figuring out how to delete a child from my jobs.xml file with a PHP script. My jobs.xml file looks like this: <jobs> <event jobid="1"> <title>jobtitle</title> <desc>description</desc> &l ...

Change the controller's classes and update the view in Angular

In my angular application, I have a popup window containing several tabs. These tabs are styled like Bootstrap and need to be switched using Angular. The code for the tabs is as follows (simplified): <div class="settingsPopupWindow"> <div> ...

When using jQuery, the search for the ID within an iframe may fail if the specified condition

I have a scenario where I need to dynamically generate an iframe and its corresponding id. Now, I need to check if the generated id already exists or not. This is what my code looks like: function createIframe(intxnId){ alert("The Id is : "+"$(&apo ...

React.js pagination - removing empty values from an array

I'm currently working on implementing pagination logic that automatically updates the page numbers when the last index is clicked. For example: 1 2 3 4 5 If a user clicks on the number 5, it should display: 2 3 4 5 6 and so forth... I have succe ...

IE7 is throwing an error saying "Object Expected" when handling the JSON response. This issue does not

Just when I thought I was ready to launch my webapp, IE7 decides to throw a wrench in my plans! I am using the JQuery Form plugin for uploading data to my server. Everything works perfectly on Chrome and Firefox, but IE7 is giving me an "Object Expected" ...

Tips for resolving the issue of dropdown menus not closing when clicking outside of them

I am currently working on an angular 5 project where the homepage consists of several components. One of the components, navbarComponent, includes a dropdown list feature. I want this dropdown list to automatically close when clicked outside of it. Here i ...

Avoid accidental overwrites in localStorage using JavaScript

I've been working on a Vue project where I'm implementing a shopping cart feature. In this setup, when the user clicks on a button, the item details are stored in localStorage and then displayed in the shopping cart interface. However, I encount ...

Show a condensed version of a lengthy string in a div using React TS

I've been tackling a React component that takes in a lengthy string and a number as props. The goal of the component is to show a truncated version of the string based on the specified number, while also featuring "show more" and "show less" buttons. ...

Send an object to query when using Router.push in Next.js

Just getting started with NextJs and I'm experimenting with passing an object to another page through a component. Let me show you the code and explain what I'm attempting to accomplish: The object I want to pass looks like this: objectEx = { ...

Utilizing Vue JS for filtering numerical data

When I search for letters, my code below works well. However, when it comes to numbers like flat_number, it gives me an error saying flat.flat_number.toLowerCase is not a function filteredList() { return this.Flats.filter((flat) => { return ( ...

Error message "Uncaught in promise" is being triggered by the calendar function within the Ionic

Can someone assist me in creating a calendar feature for my app? My concept involves a button with text that, when clicked by the user, opens a calendar. However, I am encountering an error message: ERROR Error: Uncaught (in promise): TypeError: Cannot set ...

ReactJS: Error - Attempting to convert an undefined or null value to an object is not

Encountering an issue with my Beach component, which is throwing the following error: TypeError: Cannot convert undefined or null to object ResortDetail C:/Users/JS/Desktop/MERN/KR/frontend/src/screens/Beach.js:33 30 | <p>{description}< ...

Verify the password by checking each character as you type

Currently, I am trying to implement a real-time password matching feature. Is there anyone who can provide me with the code that verifies whether the entered passwords match character by character as they are being typed, and also checks the length upon ...

Ways to retrieve a concealed DOM element from a background window

I have been struggling to display a button that is located in the background window using the jQuery code below, but unfortunately it's not functioning as expected. On my webpage, I have a hidden button that should only be visible when a user adds a ...

Raspberry Pi 4: My LED is only blinking 8 times instead of the expected 16 times

I have encountered an issue with my program run, compilation, and result. In the screenshot below, you can see that my LED is only blinking 8 times instead of the anticipated 16 times. My expectation was for the LED to blink every 0.25 seconds for a total ...

How can I interact with a v-dialog component within a child component in Vue.js using Vuetify?

Exploring Vue.js for the first time and hoping to display a login dialog upon button click. To maintain cleanliness in my code, I shifted the dialog to a child component within a parent component with nested LoginDialog. Below are snippets of the parent co ...

Can you explain the distinction between these two forms of functional components in ReactJs?

What sets apart these two code usages? In the FirstExample, focus is lost with every input change (It appears that each change triggers a rerender).. The SecondExample maintains focus and functions as intended. example import React, { useState } from &quo ...

prevent unnecessary duplicate database queries for generating metadata in the upcoming 13 or 14 instances

In the latest updates, version 13 and 14 of Next introduced the usage of the generateMetadata function as the preferred method to define all page metadata. However, a drawback of this approach is that because of the separation of logic, fetching data base ...