Accessing attribute value of selected option in AngularJS select element

I have a select tag that displays options, and I want it so that when an option is selected, the value of the data-something attribute is copied into the input element. This is just for demonstration purposes; the actual value should be sent in the form.

<input ng-model="refreshedByExample" type="text">
<select ng-model="example">
    <option value="1" data-something="valueForRefreshedByExample1">1</option>
    <option value="2" data-something="valueForRefreshedByExample2">2</option>
    <option value="3" data-something="valueForRefreshedByExample3">3</option>
</select>

Any suggestions on how to achieve this?

Thank you in advance!

Answer №1

Just made some adjustments to the code

<input ng-model="refreshedByExample" type="text">
<select ng-model="example" ng-change="refreshByExample=example"> 
    <option ng-value="valueForRefreshedByExample1">1</option> 
    <option ng-value="valueForRefreshedByExample2">2</option> 
    <option ng-value="valueForRefreshedByExample3">3</option> 
</select>

For more information, visit ng-value.

Another option is to explore ng-options if dealing with values in an array.

Answer №2

Take a look at the code snippet below, it might be what you're searching for. It's a custom directive that handles attribute types.

function exampleController($scope) {

}

function extractValue() {
  return {
    restrict: 'A',
    scope: false,
    link: function($scope, $element, $attr) {
      if ($attr.something) {
        $element[0].value = $attr.something;
      }
    }
  };
}

angular
  .module('app', [])
  .controller('exampleController', exampleController)
  .directive('extractValue', extractValue);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="app">
  <div class="row" ng-controller="exampleController">
    <input ng-model="example" type="text">
    <select ng-model="example">
      <option value="1" data-something="valueForRefreshedByExample1" extract-value>1</option>
      <option value="2" data-something="valueForRefreshedByExample2" extract-value>2</option>
      <option value="3" data-something="valueForRefreshedByExample3" extract-value>3</option>
    </select>
  </div>
</div>

Answer №3

I find that utilizing ng-options is most effective in these scenarios.

<select ng-model="example" 
  ng-options="item.value as item.id for item in array">
</select>

Here's how the array looks:

$scope.array = [
  {id: 1, value: 'valueForRefreshedByExample1'},
  {id: 2, value: 'valueForRefreshedByExample2'},
  {id: 3, value: 'valueForRefreshedByExample3'}
];

UPDATE:

For the example using values (if valueForRefreshedByExample1 isn't a string, use ngValue):

<input ng-model="example2" type="text">
<select ng-model="example2">
  <option value="valueForRefreshedByExample1">1</option>
  <option value="valueForRefreshedByExample2">2</option>
  <option value="valueForRefreshedByExample3">3</option>
</select>

You can view the examples here https://plnkr.co/edit/gfYak9zkKsAu0I5eQHx0?p=preview

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

Secure multiple confirmations with ngDialog

When using the ngDialog popup window to collect data into a $scope array, I encountered an issue where if a user clicks the confirm button multiple times, the data gets added multiple times. I attempted to use ngDisable with a $scope variable to disable ...

Is a 'Virtual DOM' included in React Native's architecture?

According to the ReactJS wiki page on Virtual DOM: React uses an in-memory cache of data structures to efficiently compute differences and update the displayed DOM in the browser. This allows developers to write code as if the entire page is re-rendered ...

Link components in Next.js now automatically add the current path when working with nested dynamic routes, making it

How can I effectively handle nested dynamic routes and utilize the Next.js Link component? Let's say I have 2 different file paths: /pages/projects/index.js <Link href={`/projects/${project.id}`} key={index}> <a>Project Name</a> ...

Error in content policy for CSS in Stripe Checkout

I am currently attempting to integrate Stripe Checkout into my Ionic App. I have created a Directive that injects the form into my content view, however, upon execution, the CSS fails due to a content policy violation: checkout.js:2Refused to load the s ...

Discover the position within a two-dimensional array

Suppose I have an array that contains objects, and each object has its own id property. In this case, I can find the index by writing: data.findIndex(x=>x.id === newData.id); Now, if data is an array of arrays of objects, how can I efficiently get two ...

What are some effective strategies for reducing excessive re-rendering of React components?

Here is how I am displaying a list of components on the screen: const MessagesContainer = ({ messages, categories, addHandler }) => { const options = categories.map(category => ( { value: category.name, label: category.name } )); ...

Selecting multiple items from a grid using the Ionic framework

I am looking to create a grid of category images in Ionic framework, where users can select multiple categories and send their values to the controller. However, I'm unsure about how to make this happen with Ionic framework. Below is the view I curre ...

An anomaly where a mysterious symbol appears in front of every dollar sign in an HTML document

I have a code written in AngularJS to display the amount in dollars. However, there is an unwanted " Â " character appearing before every " $ " character in the HTML. I am looking for a way to remove this character. Your help is greatly appreciated. Thank ...

Tips for Avoiding Database Overflow Due to Excessive AJAX Spam Requests

Let's consider a simple scenario: A create album button is used to input album data into the database. I disable the button while the request is being processed, then re-enable it upon completion. Once the processing is finished, ...

AngularJS Modals within Modals

I have a website where clicking a button triggers the opening of a modal window. Below is the essential controller code for this functionality: var modalOptions = { animation: true, templateUrl: 'somehtml.html', controller: ' ...

Problem with Pinia: nested array in an object

My unique store located within a vue3 application, contains an object called currentReservation with a property named pricings which is an array. Each pricing includes an id and quantity. When I add a new pricing, it is added to both the store and compone ...

Is it possible to create two separate Express sessions simultaneously?

I am encountering an issue with my Passport-using application that has a GraphQL endpoint and a /logout endpoint. Strangely, when I check request.isAuthenticated() inside the GraphQL endpoint, it returns true, but in the /logout endpoint, it returns false. ...

Sending template reference from one Angular component to another

I have a main grid component that includes smaller grid-item components. The majority of these grid items navigate to a specific route when clicked. However, there is one particular item that should open a modal window instead of navigating. Is there a wa ...

The Heroku app seems to be malfunctioning (Issue with deployment?)

After deploying my application that utilizes JavaScript, Express, and Node.js on Heroku, I encountered an issue where the functionality of the app is not working at all when accessed through Heroku. Interestingly, everything works perfectly fine when teste ...

Learn the best way to retrieve the highest number from a Array<String> in TypeScript or JavaScript

Can someone help me create a function in JS or TS that meets the following requirements? I am looking for a functional programming approach. ・Input type: Array(String) ・Output type: string or undefined Examples Input Result ["" ...

An unexpected runtime error occurred due to a SyntaxError: the JSON input abruptly ended during the authentication process with the next-auth module

Encountering an Unhandled Runtime Error SyntaxError: Unexpected end of JSON input when trying to SignIn or SignOut with authentication credentials. The error is puzzling as it displays the popup error message, but still manages to register the token and s ...

Storing a portion of AJAX response as a PHP variable

Is there a way to store data received through an AJAX response in a PHP variable? I want to take the value of $('#attempts_taken').val(data[11]); and save it as a PHP variable. Any help would be great! <script type="text/javascript> $(do ...

determining the preference between setTimeout and setImmediate

After reading the documentation on the node, it mentions: setImmediate(callback, [arg], [...]) This function is supposed to execute callback immediately after I/O events callbacks and before setTimeout and setInterval However, in practice, I noticed tha ...

JavaScript: Receiving an error that function is undefined when working with data binding

Why is my code showing that it's not defined while I'm attempting a simple code with data binding? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="ht ...

Filter the specific output in a generator function

I have a code snippet that I need help with. function* iterateRecord() { const db = yield MongoClient.connect(''); const collection = db.collection(''); const query = {} const cursor = collection.find(query); ...