A guide on receiving object input within AngularJS

I am working on a form that looks like this:

<input type="text" ng-model="gen.name" ng-repeat="gen in movie.genres">

The gen in the movie.genre is an object with two key-value pairs:

Object{
 id: 24,
 name : insidious
}

However, when I submit the form, I only receive the value of gen.name, but I also need to obtain the id of the gen object.

How can I modify my code to retrieve the id as well? It's important to note that there are multiple input values since they are inside an ng-repeat loop.

Answer №1

Utilizing Array.findIndex() can help you locate the id of the object associated with the selected genre name.

Try something similar to this (assuming movie.genres is an array and valueFromForm represents the value from your ng-model):

let index = movie.genres.findIndex(gen => gen.name === valueFromForm);
id = movie.genres[index].id;

This piece of code utilizes ES6 syntax, so it may require modern browsers unless transcompiled. For older browser support, consider using this alternative version:

var id = -1;
for (var i=0; i < movie.genres.length; i++) {
  if (movie.genres[i].name === valueFromForm) {
    id = movie.genres[i].id;
    break;
  }
}

Answer №2

This code snippet showcases a practical example that addresses your specific needs. I trust that this demonstration will aid you in resolving your issue:

angular.module('submitExample', [])
    .controller('ExampleController', ['$scope', '$log', function($scope, $log) {
        $scope.movie = {
            title: 'Movie Title',
            genres: [{
                name: 'Action'
            }, {
                name: 'Drama'
            }, {
                name: 'Comedy'
            }]
        };
        $scope.submit = function() {
            $log.info($scope.movie);
        };
  }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.1/angular.min.js"></script>
<div ng-app="submitExample">
    <form ng-submit="submit()" ng-controller="ExampleController">
        <input ng-model="gen.name" ng-repeat="gen in movie.genres"><br>
        <input type="submit" value="Submit">
    </form>
</div>

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 difficulties with initializing npm when trying to start a new project

As I embark on a new project with npm init, I encounter an error when trying to execute the command 'npm init -y'. The error message is displayed in the link below: https://i.sstatic.net/5vu5q.png Can anyone provide insights into what may be cau ...

Retrieve information from an external JSON file and display it in a jstree

I am trying to pass JSON data to a jstree object from an external file. The code snippet I have does not seem to be working properly. <script> $.jstree.defaults.core.themes.responsive = true; $('#frmt').jstree({ plugins: [" ...

Caution: Server Components can only pass plain objects to Client Components

My app allows users to search for care homes on a map and add new ones using a form. During development, everything was working fine. However, in production, the map was not updating to show the newly added care homes. It seemed that the API fetching the ...

Include chosen select option in Jquery form submission

Facing some challenges with a section of my code. Essentially, new elements are dynamically added to the page using .html() and ajax response. You can see an example of the added elements in the code. Since the elements were inserted into the page using . ...

What is the best way to incorporate an onmouseover event so that when the mouse hovers over an image, play/stop/pause buttons are displayed

Furthermore, each button should trigger an event on click. When the pause button is clicked, the button text should toggle between pause and continue, and the action should correspond to the displayed text. This is the HTML code I currently have: Includi ...

Facing an issue where WordPress AJAX is not showing the expected content

Currently, I am in the process of creating a WordPress website that will feature an initial display of two rows of images. Upon clicking a button, two more rows should dynamically appear. There are four key files involved in this project: case-study-ca ...

Add a third-party library file to Visual Studio

I'm currently working in Visual Studios and attempting to utilize the library provided at . However, I am encountering difficulties when trying to import the library. I have added the file to the project and attempted to use it within the Book.js (Vi ...

Consolidate test outcomes from various nodes in the stack into a single graph

Nowadays, web applications consist of a variety of different technology stacks. Developers utilize languages like Ruby, Python, PHP, JavaScript, and C for the backend, as well as frameworks such as AngularJS and EmberJS for MVC/client-side code. To ensure ...

Is it necessary for me to manually delete the node in JavaScript, or does the garbage collector handle that task automatically?

In order to remove the final node from a circular linked list using JavaScript, I plan on iterating to the second-to-last node and then connecting it back to the first node. This process effectively detaches the last node from the chain. My question is, ...

Is it possible to generate a Token in Nexus for private packages without using the UI interface?

We have implemented Sonatype Nexus Repository ManagerOSS 3.29.0-02 and are currently facing an issue in generating a TOKEN that can be used with .npmrc following this specific structure: registry=http://NEXUS-IP:8081/repository/GROUP-NAME http://NEXUS-IP:8 ...

Alternating the tooltip icon based on the field's condition

Looking for a way to create a tooltip for an input field that involves changing icons based on certain conditions. An example scenario is the password field in a registration form. Seeking advice on the best approach to achieve this. Currently, here' ...

"Step-by-Step Guide: Integrate Cloudinary Upload Widget with Angular Framework

Struggling with integrating the Cloudinary Upload Widget into my Angular project. I followed the example code provided by Cloudinary, but it's not functioning as expected. It seems like there's a missing import or package needed to access the clo ...

The Viadeo Social Toolbox seems to be encountering technical difficulties at the moment

I attempted to utilize a Viadeo Social Toolbox, specifically the Viadeo Share Button, but it seems to be malfunctioning in certain browsers? I came across some outdated viadeo share URLs like this: http://www.viadeo.com/shareit/share/?url=${url}&title ...

Transforming a pseudo element from horizontal to vertical orientation

I have a unique snippet of code that generates an element at the bottom of a div to serve as an inventive 'arrow/pointer' pointing down. Now, I am seeking assistance in tweaking the script so that the 'arrow/pointer' directs towards th ...

Creating a personalized audio player using HTML

I have created a design for an audio player that I would like to implement using the HTML audio player element. https://i.sstatic.net/vJpGg.jpg When I tried <audio></audio>, it just displayed the default player: https://i.sstatic.net/nyNj8.j ...

The API for /api/addproducts has been resolved without a response being sent, potentially causing delays in processing requests

A response was not sent for the /api/addproducts API, which can lead to delays in processing requests. Below is the code for the add product API that I have been working on: I've debugged it using the console, but I'm still struggling to find t ...

What is the reason for the error that is being caused by using arrow functions in my code

I'm currently working on a React application, but I keep running into errors that are causing issues. Here is the code snippet in question: import React from 'react'; import { Link } from 'react-router-dom'; const LINKS = [ { to ...

Hmm, I seem to be encountering an error where res.sendStatus is not recognized as a function. What could be causing this

For the last few months, I have been immersed in Node.js/Express to create a REST Api. However, I've hit a roadblock with an async function in my controller.js file. The callback function is successfully receiving the client's request, but when i ...

What is the best way to change a canvas into an image while preserving transparency?

Currently, I am attempting to modify a weather radar image with a black background by making the background transparent using canvas. However, when I view the modified image, instead of transparency, the background now appears as a red and black checkerboa ...

Turn on / off Button Using a Different Button

I am currently working on an application that is designed to create teams using button selectors. There are two initial teams in play: the (available team) which consists of two buttons - one for selecting a player and populating the player name into the ( ...