Using AngularJS to filter options in a dropdown list and trigger a function with ng-change

I have a dropdown menu that is being formatted using filters to display the text in a certain way. I need to send the selected item's ID value to the controller instead of just the name:

<select 
                ng-model="my_field" 
                ng-options="q.name as (q.name | filter1 | filter2) for q in my_fields track by q.id"
                ng-change="controllerMethod(my_field)"
                required>
                </select>

// Controller
    function controllerMethod(selected_field){
       console.log(selected_field);
    }
    $scope.controllerMethod = controllerMethod;


// Filters
    angular.module('app')
        .filter('filter1', function(){ 
            return function(str_value) {
                return str_value ? str_value.split('_').join(' ') : "";
            }
        })

        .filter('filter2', function(){ 
            return function(str_value) {
                return (!!str_value) ? str_value.charAt(0).toUpperCase() + str_value.substr(1).toLowerCase() : '';
            }
        })

Previously, without the filters, all object data was being sent to the controller. Now, only the name is being passed. How can I pass the ID of the selected object instead?

Thank you!

Answer №1

I suggest updating your ng-options to the following:

ng-options="q as (q.name | filter1 | filter2) for q in my_fields track by q.id"

The current setup you have causes the track by expression to result in q.name.id, which may lead to undefined behavior. By making the modification above, it should instead evaluate to q.id, aligning with your intended outcome. Feel free to reference this jsfiddle to confirm if this adjustment meets your requirements.

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

How to extract IDs from a URL in Angular

I'm facing an issue with retrieving the first id from an image URL. Instead of getting the desired id, I am receiving the one after the semicolon ("id" = 1). I have tried various methods but haven't been successful in resolving this issue. Any su ...

Implementing the firebase-admin SDK module into an AngularJS project

How can I integrate firebase-admin into my AngularJS project? Any assistance on this matter would be greatly appreciated! Thank you. ...

Adjusting the settimeout delay time during its execution

Is there a way to adjust the setTimeout delay time while it is already running? I tried using debounceTime() as an alternative, but I would like to modify the existing delay time instead of creating a new one. In the code snippet provided, the delay is se ...

Delete a Woocommerce item from the shopping cart using ajax/fetch technology

My issue lies with the removal of products from the cart in Woocommerce, specifically involving WC_Cart::remove_cart_item. The error messages I am encountering are: POST http://localhost:3000/esport/wp-admin/admin-ajax.php [HTTP/1.1 500 Internal Server Err ...

Transferring information between AngularJS and Express/Node without using AJAX

My application is built using AngularJS on a node/express backend, with user authentication handled by passport. After a user signs in or signs up, the communication between my Angular controllers and express is done through $http ajax/xhr calls. The form ...

Encountering a 500 internal server error while trying to submit a form via AJAX and

I'm a beginner in PHP and I'm facing issues with sending test emails from my local host. My form consists of 3 fields, and I want the user to be able to submit the form and see a success message without the page refreshing. Although I have set u ...

"Encountering a hang while using the .save() function and only

Issue with storing data in MongoDB This is only my second attempt at saving data to a database and I am still relatively new to the process. I have a form on my HTML page that sends string data to be saved in a MongoDB database. I successfully connected t ...

Refreshing a value in the view at regular intervals using a filter in Vue

Trying to create a countdown timer with vue, but the view is not updating. Here are my app.js and index.html: var nowDate = new Date; var nextNewYearsEve = new Date(nowDate.getFullYear(), 11, 31, 23, 59, 59, 59); var timeLeftToNewYearsEve = nextNewYears ...

Stellar.js is malfunctioning

I've been attempting to implement a parallax effect using Stellar.js with two image tag elements, but I'm encountering issues. Despite trying various configurations, including following the Stellar.js creator's tutorial scripts closely, noth ...

Guide to creating intricate designs on an HTML5 Canvas, one pixel at a time

Imagine a scenario where there is a 900x900 HTML5 Canvas element involved. In this case, there is a function named computeRow, which takes the row number as a parameter and returns an array of 900 numbers. These numbers represent colors ranging from 0 to ...

The function image.getState is not recognized (when trying to implement ol in an Angular project)

I attempted to integrate the code provided in an angular(4) application at the following link: However, I encountered an error every time I tried to launch the browser. To start with, here are my imports (both libraries were locally installed via npm): ...

The issue of page content failing to refresh when loaded using AJAX technology

My script utilizes AJAX to dynamically load specific pages on a website. These pages display information that updates based on the current time. However, I have encountered an issue where the page content remains static when loaded through AJAX, almost as ...

Display an assortment of various categories once every other time

As a novice AngularJS user, I am looking to showcase a collection in my HTML code using a specific directive: displaying items alternately on the left and right side. For example, the first item on the left, the second on the right, the third on the left, ...

I often find myself pondering the significance of objects such as [, thisArg]

At times, I delve into JavaScript code on MDN and come across some confusing syntax like [, thisArg]... for instance, arr.map(callback(currentValue[, index[, array]])[, thisArg]) In this scenario, I am aware that a callback function is required. But what ...

Identifying the user's location within the application and dynamically loading various Angular scripts

Currently, I am working on a large-scale web application using Laravel and Angular. In this project, I have integrated various angular modules that come with their own controllers, directives, and views. One challenge I am facing is the need to load diffe ...

An Alternative Approach for Executing a Function within an AngularJS Directive

I am currently working on a unique element directive that displays a user's picture and name. This directive has various configuration attributes, one of which is the uc-on-hover attribute. The purpose of this attribute is to determine what element sh ...

Storing client time data in a database using Node.js

Just starting out with Node.js so bear with me while I learn the ropes. I successfully set up a basic TCP server using the guide here In my current project, users will connect to the server from a web browser and I'm interested in capturing the TCP ...

Azure experiencing issue with MUI Datepicker where selected date is shifted by one day

I have developed a unique custom date selection component that utilizes Material UI and Formik. This component passes the selected date value to a parent form component in the following manner: import React from 'react'; import { useField } from ...

How can one determine if an array in javascript contains anything other than null values?

I am dealing with an array that typically contains: [null, null, null, null, null] However, there are instances where the array may change to something like: ["helloworld", null, null, null, null] Instead of using a for loop, I am curious if it is po ...

Altering the input type of a cloned element in Internet Explorer results in the loss of the value

When I have checkbox inputs displayed in a modal with preset value attributes, upon clicking "OK", I clone them and change their input types to hidden, then append them to a div in the document body. However, when trying to retrieve their values using jQue ...