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

Unexpected behavior from vuelidate triggered on blur

I have implemented vuelidate for form validation. My goal is to validate user input either when they move to the next input field or click outside of the current one. <div class="form-group col-md-6" :class="{invalid: $v.partner.email.$ ...

Creating JavaScript classes based on JSON schemas

I have a JSON file containing information and data related to my work, presented in the following format: { "Employees":[ { "id": 1, "fullName": "Test Test" } ], "Infos":[ { "id": 1, ...

Angular 15 experiences trouble with child components sending strings to parent components

I am facing a challenge with my child component (filters.component.ts) as I attempt to emit a string to the parent component. Previously, I successfully achieved this with another component, but Angular seems to be hesitant when implementing an *ngFor loop ...

Using Vue's computed property setter with an object as a prop

I have a new concept for an input component where different objects can be passed, displayed as CSV, and allow for text editing/validation with style changes based on validation results. Check out the code snippet I've been working on: <div id=&quo ...

Executing API call utilizing the Request module within a node.js application

In my node.js app, I have a request call that looks like this: request({ url:chanURL, qs:chanProperties}, function(err, response, body) { if(err) { console.log(err); return; } body = JSON.parse(body); (function (body) { Objec ...

What is the best way to eliminate a particular element from an array produced using the .map() function in

I am experiencing an issue with my EventCell.tsx component. When a user clicks on the component, an event is created by adding an element to the components state. Subsequently, a list of Event.tsx components is rendered using the .map() method. The problem ...

Enhancing Bootstrap UI Typeahead to Display Multiple Fields in Results List

Having encountered the same issue as described in this question: Bootstrap-UI Typeahead display more than one property in results list? I made adjustments to the Plunker provided in the answer to fit my requirements: http://plnkr.co/edit/FdkvCUUD3ob7dt2 ...

The redirect function is failing to carry the "req" parameter

Express Routes Troubleshooting app.get('/auth/google/redirect', passport.authenticate('google'), (req, res) => { console.log('req.user:', req.user) //>>>>>Outputs {username: 'bob', id: '.. ...

The utilization of conditional expression necessitates the inclusion of all three expressions at the conclusion

<div *ngFor="let f of layout?.photoframes; let i = index" [attr.data-index]="i"> <input type="number" [(ngModel)]="f.x" [style.border-color]="(selectedObject===f) ? 'red'" /> </div> An error is triggered by the conditional ...

Struggling to get a package running in Next.js that is functioning perfectly in ReactJS

Link I have integrated the JSME React npm package into my application to utilize the JSME editor. While this package works seamlessly in a ReactJS environment, I am encountering issues when trying to use it in a Next.js project. I am receiving an error mes ...

What are the best strategies for managing a collection of service requests in AngularJS?

I require assistance with Angular JS. When clicking on a button, I need to make 400 service calls in an iPad hybrid application. However, this process is taking too long. Can anyone suggest how to optimize the service calls? Currently, I am using: forEa ...

What is the best way to pause or stop the $interval when exiting the ui-state

When using Angular with UI-router, I encountered a problem with $interval in a controller. Here is the code snippet to illustrate the issue: $scope.Timer = null; $scope.startTimer = function () { $scope.Timer = $interval($scope.Foo, 30000); }; $sco ...

``So, you're looking to retrieve a collection of objects that have a OneToMany

Is there a way to retrieve a list of objects with a OneToMany relation using TypeORM's queryBuilder? This is the desired output: { "id": 1, "firstName": "Bob", "lastName": "Sparrow", "orders": [ { "id": 1, "name": "Very Big Or ...

What is the best way to conceal a row when a particular field is devoid of content?

Is it possible to hide an entire table row if a field is empty? For example: https://i.sstatic.net/tMW7L.png If a certain field is empty, I want the entire row to be hidden, either using JavaScript or jQuery. I have tried some methods but none of them fu ...

Issue with SweetAlert2 cancel button being unresponsive while an ajax request is in progress

I have a custom function triggered when a dropdown item is selected, which triggers a sweetalert2 popup. Here's the function: function SwalPopup(ip, method) { var methodmsg = method.charAt(0).toUpperCase() + method.slice(1); swal.fire({ ...

I am experiencing difficulty with Three.js rendering textures from my planet constructor function

I am facing an issue with my function that is supposed to create a 3D object (a planet) using orbital parameters and texture images from a dataset. Strangely, the textures are not rendering when I use StandardMaterial or PhongMaterial, even though they wor ...

Run XQuery dynamically in JavaScript and store the outcome in a JavaScript variable

Looking to achieve the following: Running a dynamic XQUERY stored in a JavaScript variable example var myxquery = For Channels.Channel where Channel/availability = yes And Channels.Channel/Label = 'CNN' Return EXIST(Channels.Channel/Id)&apo ...

Creating a sleek animated analog clock using CSS and jQuery

I am facing a small issue with my CSS3/jQuery analog clock. Currently, the movement of the clock hands is a bit abrupt. I would like the animation to be smooth. I attempted using transition: all .1s, but it gets messy when the clock hands reach the top po ...

Issue with AngularJS: Unable to receive response from REST API call

I'm currently working on developing a basic login form using AngularJS and a RESTful web service. While I've been able to successfully call the RESTful web service, I am struggling to retrieve the response. 1) Login Form: <div class="col-md- ...

Achieving both positive and negative styling in AngularJS with ng-class: A guide

I'm currently working on an application that requires indicating red for negative values and blue for positive values in a calculation. <td class="amount debit"> <input type="text" class="form-control" ng-model="vm.model.form.amount_debi ...