Issue with AngularJS: The select dropdown fails to update the selected option when the bound scope variable changes

I am facing an issue with a select control in my Angular app. The options for the select are generated dynamically from an array of objects in the scope. When I try to pre-select a specific option on app init by changing a bound variable on the scope, it doesn't work properly.

Interestingly, it works fine when the ng-option of the select returns a string instead of the full object. I'm not sure if this is a bug in Angular or if I am missing something in my implementation.

Here is the code snippet:

<div ng-controller="selectCtrl" ng-app>
    Doesn't work when select's ngModel value is object:<br />
    <select ng-model="valueObject" ng-options="o.label for o in options"></select><br />
    <pre>{{valueObject | json}}</pre>

    Works when select's ngModel value is string:<br />
    <select ng-model="valueString" ng-options="o.value as o.label for o in options"></select>
    <pre>{{valueString | json}}</pre>    

JS:

function selectCtrl($scope) {    
   $scope.options = [
       {label: 'a', value: '1', someId: 333},
       {label: 'b', value: '2', someId: 555}
   ];    
   $scope.valueObject = {label: 'a', value: '1', someId: 333};
   $scope.valueString = '1';
};

JS Fiddle: http://jsfiddle.net/apuchkov/FvsKW/6/

Answer №1

"Track by" statement must be utilized in order for the example provided in my original question to function properly. For more information, please visit:

Check out the updated JsFiddle link here: http://jsfiddle.net/apuchkov/FvsKW/9/

Here is the HTML code:

<div ng-controller="selectCtrl" ng-app>
    When the select's ngModel value is an object, it does not work:<br />
    <select ng-model="valueObject" ng-options="o.label for o in options"></select><br />
    <pre>{{valueObject | json}}</pre>

    However, it does work when the select's ngModel value is an object AND 'track by' expression is used:<br />
    <select ng-model="valueObject" ng-options="o.label for o in options track by o.value"></select><br />
    <pre>{{valueObject | json}}</pre>
</div>

And here is the corresponding JavaScript code:

function selectCtrl($scope) {    
    $scope.options = [
        {label: 'a', value: '1', someId: 333},
        {label: 'b', value: '2', someId: 555}
    ];    
    $scope.valueObject = {label: 'a', value: '1', someId: 333};
};

Answer №2

It is important to note that objects sharing the same keys and values are not considered equal to each other (refer to ES 5.1 Specification 11.9.6):

// Determine if x and y reference the same object in memory.
// Return true if they do, otherwise return false.
> var first = {name: 'John', age: 30, id: 123}
> var second = {name: 'John', age: 30, id: 123}
> first === first
true
> second === second
true
> first === second
false
> first == second
false

To resolve the issue, update

$scope.valueObject = { /* similar object */ }
to
$scope.valueObject = $scope.options[0]
and everything should function correctly.

Answer №3

This code snippet is designed to be used with a specific controller:

function chooseCtrl($scope) {
   $scope.selections = [
       {name: 'apple', rating: '4', identifier: 123},
       {name: 'banana', rating: '5', identifier: 456}
   ];    
   $scope.selectedItem = $scope.selections[0];
};

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

Ways to fill ng-style with a CSS object

Creating a dynamic form to manipulate CSS properties in real time has been my latest project. I've managed to define the CSS property names and values within an object, but now I'm struggling to style the item elegantly on the page as the user in ...

How can I showcase a chosen name in a <p> tag using a Select dropdown, and then pass the selected ID to a controller in AngularJS

I am working with a select input in my HTML that is populated using ng-options. My goal is to display the selected NAME below, while sending the selected ID back to the controller. I am able to access the required id from ng-model="user.category". How ca ...

Guide to adding a personalized HTTP header to ajax request using JavaScript or jQuery

Is there a way to create a custom HTTP header using JavaScript or jQuery? I've tried the code below but it's giving me an error of 405 Method not Allowed. I'm using the POST method, but in the request it shows as OPTION. The status code is ...

Utilizing Data Filters to Embed HTML in Vue.js?

I have been attempting to utilize the Filter feature in Vue.js to insert HTML tags within a String. The documentation indicates that this should be achievable, however, I am not having any success. The objective is for the data to be just a String that is ...

Issue with Angular form not triggering ng-submit functionI am facing a problem where

Issue with angular submission: I've been trying to implement a simple submission feature using angular, but the $scope.account_create.submit function isn't getting called upon submission. I have added the name attribute to the form and ensured th ...

"Geolocation within the boundary of a map: what's the message

Can text be placed inside a shape using ng-map? <ng-map default-style="true" zoom="18" center="53.25564575, -113.81401062" map-type-id="SATELLITE"> <shape name="rectangle" editable="true" draggable="true" bounds="[[53.2559199723254, ...

Sticky positioning with varying column widths

How can I create HTML and CSS columns that stick together without manually specifying the "left:" parameter every time? The current example in the fiddle achieves what I want, but requires manual setting of the "left:" value. Is there a way to make this m ...

Remove the click event once the sorting process has been completed

I am currently working on a project that involves creating a list of sortable images using jquery sortable. Users can easily drag and drop the images for sorting purposes. Additionally, each image's parent anchor has a click event attached to open it ...

What strategies can be implemented to maximize the effectiveness of Office ribbon commands within an AngularJS application?

Currently, I have developed an Office add-in using AngularJS (version 1.4) and ASP.NET MVC 4.5. The Angular controller and service JS files contain a significant amount of functionality that has already been implemented. Lately, I have been exploring the ...

When using node.js express, the req.body object does not yield any results

My web server setup with express appears to be functioning correctly, however, I am encountering an issue where the req.body returns nothing. Despite not receiving any errors, the console.log(req.body) doesn't show anything in the console output. Stra ...

The functionality of JSON.stringify does not take into account object properties

Check out the example on jsfiddle at http://jsfiddle.net/frigon/H6ssq/ I have encountered an issue where JSON.stringify is ignoring certain fields. Is there a way to make JSON.stringify include them in the parsing? In the provided jsfiddle code... <s ...

Transform the array within a callback function

Seeking assistance: I am grappling with the challenge of constructing an array of results within a loop of MySQL results. The ultimate goal is to populate an array with normalized objects derived from raw data. Any guidance would be greatly appreciated! ...

The drag-and-drop application failed to upload a video using Ajax

I am currently working on an application that allows users to upload files to a server with a drag and drop function. The app is functioning well for images, but occasionally encounters issues when trying to upload videos. I'm not certain if there&apo ...

Listening for events on an array of elements using jQuery

My task involves populating an array with elements using the .each() method and the $(this) selector. (function($){ var elements = new Array(); var index = 0; $("img").each(function() { if($(this).attr("attribute")){ $(thi ...

Generate selection choices by looping through a JSON document

I am attempting to develop a search box that will provide autocomplete suggestions based on user input from a key-value pair in a json file. I initially thought using datalist would be the most suitable approach for this task, however, upon running the cod ...

Tips for incorporating JavaScript into .ascx pages

What are some ways to incorporate javascript in .ascx files? ...

React is indicating that returning functions is not appropriate as a React child. This issue may arise if you accidentally return a component instead of <Component /> within the render method

Check out the main game.js and app.js files: //Here is the code in game.js// import React, { Component } from "react"; class Game extends Component { constructor(props) { super(props); this.state = { num: 0 }; this.numPicker = this.numPi ...

"Use Highcharts to visually compare the data from one month in two different years

How can I use Highcharts Columns to compare data from two different years within the same month? Check out the example image below: https://i.sstatic.net/8MMsA.png The data structure is as follows: myData[0] = { data1:"0.00", data2:"0.00", data3:"868.0 ...

Searching in Angularjs made personal

I am a newcomer to angularjs and I am currently working on a project that involves creating a table with text boxes in each column for searching. The columns include Name, Date of Hike, Gender, Salary, and another Salary field. When I initially searched fo ...

Ant Design radio group buttons are currently dysfunctional

I'm having some trouble with radio group buttons. Can anyone assist me with this issue? (your help is greatly appreciated) Current Problem: Radio Group buttons are unclickable. Not sure where the issue lies! Technologies Used: React hooks, styled-co ...