When I select an option with an object, ng-model is receiving '[object Object]' instead of the actual object for <select> element

Referencing an example from Angular documentation: this link, specifically the section on "Using ngValue to bind the model to an array of objects."

In the index.html file:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8>
  <title>Example - example-select-ngvalue-production</title>


  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <script src="app.js"></script>



</head>
<body ng-app="ngvalueSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="ngvalueselect"> ngvalue select: </label>
    <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
      <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <pre>model = {{data.model | json}}</pre><br/>
</div>
</body>
</html>

The app.js file:

(function(angular) {
  'use strict';
angular.module('ngvalueSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
          {value: 'myString', name: 'string'},
          {value: 1, name: 'integer'},
          {value: true, name: 'boolean'},
          {value: null, name: 'null'},
          {value: {prop: 'value'}, name: 'object'},
          {value: ['a'], name: 'array'}
     ]
    };
 }]);
})(window.angular);

Check out the Plunker here: Plunker Link

The issue at hand is that when a user selects an item from the drop-down, instead of the object being passed as Object, it displays "[object Object]" in the ng-model of the select.

Angular suggests using ng-options instead of repeating options individually, but extra logic like ng-style needs to be applied differently for each option in this case.

So, the question remains: How can we ensure that the selected object is passed correctly as an Object in the ng-model of the select element?

Answer №1

Why go for ng-options?

<select size="6" name="ngvalueselect" ng-model="data.model" ng-options="item.value as item.name for item in data.availableOptions" multiple></select>

Check out this working plunker https://plnkr.co/edit/zVzTI6sR6LywC9vcZRkn

Answer №2

In my opinion, the correct format for your select statement should resemble the following:

<select size="6" name="ngvalueselect" ng-model="data.model" ng-options="option.value as option.name for option in data.availableOptions" multiple>

Therefore, there is no need for separate option items.

Answer №3

$(this).find(":selected").data("value")

<form name="myForm">
    <label for="ngvalueselect"> ngvalue select: </label>
    <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
      <option ng-repeat="option in data.availableOptions" data-option="{{option.value}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <pre>model = {{data.model | json}}</pre><br/>
</div>
</body>
</html>

and in case of utilizing jquery:

$(document).on("change","select",function(){
    var objectOrStringReturend = $(this).find(":selected").data("value");
});

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

Using CSS to apply a gradient over an img element

Looking to add a gradient overlay to an <img> tag with the src attribute set to angular-item. Here's an example: <img src={{value.angitem.image}}> I attempted to create a CSS class: .pickgradient { background: -webkit-gradient(linear ...

Using the reduce method in JavaScript or TypeScript to manipulate arrays

Just exploring my culture. I have grasped the concept of the reduce principle var sumAll = function(...nums: number[]):void{ var sum = nums.reduce((a, b) => a + b , 0); document.write("sum: " + sum + "<br/>"); } sumAll(1,2,3,4,5); The r ...

Spinning text within a circular rotation in CSS

Looking for guidance on how to center the "hallo" text inside a circle? Currently experiencing issues with the circle display in IE8 and Firefox. Any suggestions on how to fix this would be greatly appreciated. And here is the link to my code snippet: CSS ...

Troubleshooting: Datepicker not appearing in Bootstrap

Here is the detailed markup for the datepicker component: <div class="form-group row"> <div class="col-xs-3 col-md-offset-9"> <label class="control-label">Pick Date</label> <div class="input-group date" id="dp3" data-d ...

How come the Qunit counter doesn't seem to ever reach its expected target value during this test?

I'm currently stuck on a Qunit test related to jQuery Mobile's listview.filter extension. I can't figure out how the variable _refreshCornersCount ends up with a value of 3. Below is the section causing confusion. module( "Custom search ...

Conceal the block quotes while substituting with a newline

My HTML page contains numerous comments enclosed in blockquotes. I attempted to implement a feature that allows users to hide all the comments with just one click by using the following JavaScript code: const blockQuotes = document.getElementsByTagName(& ...

"The text() or json() methods in Javascript's fetch function never seem to resolve, leaving the operation in a perpetual

In my new nextjs 13 project, I'm attempting to perform a fetch operation (unsure if it's related to JavaScript or nextjs) and using console.logs to monitor the code execution. let url = `${BASE}/${module}/${path}`; url += "?" + ne ...

Unusual shifting movement observed in Angular UI bootstrap carousel

Currently, I am working on a project that involves incorporating a carousel to showcase various content. Instead of dynamically creating the slides using ng-repeat, I need to transfer some content from other parts of the DOM into the slide. My objective i ...

Avoid re-rendering the page in Nuxt when adjusting dynamic parameters

My page has two dynamic parameters that trigger the fetch method to run again when the URL params are changed. I want to avoid this behavior. Fetch Method: async fetch() { await this.getFlightResult(); } Get Result Method: async getResult() { th ...

Tips for implementing HTTP requests in Angular 2 without TypeScript

The demonstrations provided by the angular team only illustrate injecting Http for typescript. https://angular.io/docs/js/latest/api/http/Http-class.html How can this be accomplished in JavaScript? import {Http, HTTP_PROVIDERS} from 'angular2/http& ...

Generating a highchart by retrieving JSON data using AJAX

I'm currently working on generating a basic chart on a webpage using data from a MySQL database that is fetched via a MySQL script. My main challenge lies in understanding how to combine the ajax call with the necessary data for the chart. I'm n ...

Invoke a function or variable based on a string parameter within a JavaScript/React function dynamically

I am currently exploring ways to dynamically call a function based on a string or reference a variable using a string. For example: import React, {useState} from 'react' const array = [ { text: 'count1', setFunctionName: &apo ...

What is preventing my Button's onClick() method from being effective?

Below is a snippet of my HTML layout using the sciter framework: <div id="volume_micphone_slider" style="z-index:1;"> <input id="volume_slider" class="volume_slider" type="vslider" name="p1c" max="100" value="20" buddy="p1c-buddy" /> < ...

In AngularJS, the use of the '+' operator is causing concatenation instead of addition

Looking for assistance with my TypeScript code where I've created a basic calculator. Everything is working as expected except for addition, which seems to be concatenating the numbers instead of adding them together. HTML CODE : <input type="tex ...

How would the input value change if the clock time changed?

I am working with dynamic inputs that allow me to add and delete rows with inputs. These inputs include material-ui timepickers, which have an icon of a clock next to the input field. When I click on the clock icon, a clock widget appears. However, the val ...

Tips for efficiently delivering the create-react-app index file from your server

I have encountered a challenge in my development work with create-react-app. I am looking to serve the index.html file from the backend initially, but I am facing difficulties in achieving this goal. The main reason behind this desire is to customize the ...

How can Observables be designed to exhibit both synchronous and asynchronous behavior?

From: Understanding the Contrasts Between Promises and Observables In contrast, a Promise consistently operates asynchronously, while an Observable can function in synchronous or asynchronous manners. This presents the opportunity to manipulate code in ...

What is the best method to display an asterisk (*) in red while using React and Material UI

In my form, I want to indicate required fields with a red star (*). Is there a way to display the star in red color? Also, why does the border turn blue when I click on an input field? Here is the code and screenshot for reference: https://codesandbox.io/ ...

What approach does JavaScript take when encountering a value that is undefined?

Having recently delved into JavaScript and exploring a book, I came across an interesting example in the recursive chapter: function findSolution(target) { function find(current, history) { if (current == target) return history; else if (c ...

Utilizing a function as an argument in another function (with specified parameters)

I’m stuck and can’t seem to solve this problem. In my function, the parameter filter needs to be a function call that accepts an object created within the same function: function bindSlider(time, filter) { var values = { min : 8, max : ...