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

Inquire about understanding Mean.js through form submission

Hey there, I'm looking to create a search engine for an application using JS MEAN. I have a database with various elements and I want users to fill out a form to see the results in a separate view. I haven't had much luck so far, I've don ...

Updating Array Values in AngularJS based on Input Text Box Modifications

In my application, there is a text box that looks like this - <input type="text" class="form-control" id="inputID" name="ItemId" ng-model="inputItemId" ng-required="true" ng-blur="addValueToArray(inputItemId)"/> The user has the ability to add or r ...

Dealing with Content-Range for pagination in Restangular: A comprehensive guide

When working with an API that returns the header "Content-range" for lists, how can I efficiently retrieve and parse this header value using Restangular? Do I need to create a custom function for this task? Is there an existing method in Restangular that ...

Can you explain the distinction between using get() and valueChanges() in an Angular Firestore query?

Can someone help clarify the distinction between get() and valueChanges() when executing a query in Angular Firestore? Are there specific advantages or disadvantages to consider, such as differences in reads or costs? ...

Customizing URLs in AngularJS using ui-router allows for more personalized

Hey there, I've encountered an issue with my app. Users can sign up as merchants and have their own store name with a URL structure like this: http://localhost:8000/#/storename The problem arises when the default homepage subpages, such as contactus ...

Tabulate the number of items in an array based on the month and

I have received JSON data with dates indicating the creation time of multiple parcels. I want to analyze this data and calculate the total number of parcels created in each month. I am new to this process and unsure about which thread on Stack Overflow can ...

Unexpected Behavior Arises from Axios Get API Request

Below is a functional example in my CodePen showing what should be happening. Everything is working as intended with hard coded data. CodePen: https://codepen.io/anon/pen/XxNORW?editors=0001 Hard coded data: info:[ { "id": 1, "title": "Title one ...

A guide on incorporating multiple nested loops within a single table using Vue.js

Is it possible to loop through a multi-nested object collection while still displaying it in the same table? <table v-for="d in transaction.documents"> <tbody> <tr> <th>Document ID:</th> &l ...

Module is absent in JavaScript but present in TypeScript

As I delve into coding a vscode extension by following a tutorial, I encountered an issue with importing in my server.ts file. The directory structure looks like this: ...

Tips on avoiding scrolling when toggling the mobile navigation bar:

While working on a website using HTML, CSS, and BS3, I have created a basic mobile navigation. However, I am facing an issue where I want to disable scrolling of the body when toggling the hamburger button. The problem arises when the menu is toggled on, ...

What could be the reason why I am unable to load the ejs file?

https://i.stack.imgur.com/91bPg.png Issue: Unable to find the "index.ejs" view in the views directory ...

Tips for creating fonts that adjust depending on the length of characters

Is there a way to adjust the font size of a paragraph based on the space available in its containing div, depending on the length of characters? For instance: p{ font-size:15px; } <div class="caption"> <p>Lorem ipsum dolor sit amet, consect ...

Exploring Django with Selenium: How to Extract Page Content Using find_element

I have been attempting to extract the text 'Incorrect Credentials' using selenium. Here is what I have experimented with... message_text = self.driver.find_element(By.XPATH, '//*[@id="toast-container"]/div/div[1][@class="ng-binding toast-t ...

Using the div id within JavaScript to create a new Google Maps latitude and longitude

Here is my code for locating an IP using Google Maps. I am trying to set new google.maps.LatLng('< HERE >') to <div id="loc"></div>. How can I achieve this where the result will be 40.4652,-74.2307 as part of #loc? <scrip ...

How to Monitor Store Changes within a Vue File Using Vue.js

I am working with 2 vue files, header.vue and sidebar.vue. Both components are imported into layout.vue. Here are the steps I am following: 1. Initially, when the page loads, I update the store in header.vue with some values inside the created hook. 2. ...

Who needs a proper naming convention when things are working just fine? What's the point of conventions if they don't improve functionality?

I am a newcomer to the world of JavaScript programming and stumbled upon this example while practicing. <html> <head> <script type="text/javascript"> function changeTabIndex() { document.getElementById('1').tabIndex="3" d ...

Incorporating unique symbols into a RegExp object during its creation using a variable

As a beginner, I am currently working on a small function that will allow users to pick up objects and add them to an inventory by entering text in a box. In my setup, there is a text box with the id "commandBox" and a button that triggers the 'pickU ...

Gaining entry into a JSON object

I'm currently working on a web page that utilizes API data from the Breaking Bad website. I have received this data in JSON format, but I am struggling to figure out how to access only the objects where the "author" is "Walter White." Here is the data ...

Incorporating a division using the data() method

Currently, I am in the process of generating a list of flash SWFs. The data for this list is retrieved through an ajax call, which returns a JSON object. To populate the rows with data, I utilize my makeAppRow function. makeAppRow = function(myData) { ...

Using AngularJS to apply conditional ngStyle

Can I achieve a similar effect to this using the following code: <span data-ng-style="vm.myFlag ? 'background-color:{{myObject.color}};padding:2px;border-radius:2px;' : ''"> The if-else statement in the above code does not work ...