Angular - Manipulating the selected option in a select box from the controller

My issue involves a select box that is defined in the following manner:

 <select ng-model="selectedSupplier" ng-options="supplier.name for supplier in suppliers">
 </select>

Within my controller, there is a button that doesn't have any real function but helps to highlight a problem I'm encountering when trying to change the selected value programmatically:

When this particular function is executed, it successfully sets the options in the select box and also updates the selected option:

$scope.foo = function() {
    var foos = [{"id":1,"name":"No 1"},{"id":2,"name":"No 2"},{"id":3,"name":"No 3"},{"id":4,"name":"No 4"}];
    $scope.suppliers = foos;
    $scope.selectedSupplier = foos[2];
}

However, when I modify the function as shown below, it still sets the options correctly, but the selected option ends up being a blank one rather than the one I intended:

$scope.foo = function() {
    var foos = [{"id":1,"name":"No 1"},{"id":2,"name":"No 2"},{"id":3,"name":"No 3"},{"id":4,"name":"No 4"}];
    $scope.suppliers = foos;
    $scope.selectedSupplier = {"id":3,"name":"No 3"};
}

I'm puzzled by this behavior. Is there a way to set the selected option using an object different from the original ones defined?

Answer №1

There seems to be an equality/identity concern here. The specific

 $scope.selectedSupplier = {"id":3,"name":"No 3"};

Does not match the object in your foos collection. Despite having the same data, they are distinct references.

$scope.selectedSupplier === foos[2] // false

You correctly point to the object within your array in the initial example.

$scope.selectedSupplier = foos[2];

Answer №3

Within this specific line:

$scope.selectedSupplier = {"id":3,"name":"No 3"};

You are assigning a separate object to $scope.selectedSupplier, which is not included in the options list. There is no automatic deep comparison - for complex objects, you should assign the actual object itself.

If your intention is to assign the selected value based on the id property, consider using this code snippet:

var idToAssign = 2;
for (var i = 0; i < $scope.suppliers.length; i++) {
    var curSupplier = $scope.suppliers[i];
    if (curSupplier.id == idToAssign) {
        $scope.selectedSupplier = curSupplier;
        break;
    }
}

Answer №4

After experimenting, I discovered that by removing the quotation marks " around object keys (id not "id") in JavaScript, the code still functioned as expected.

  $scope.foo = function() {
       var foos = [{id:1,name:"No 1"},{id:2,name:"No 2"},{id:3,name:"No 3"},{id:4,name:"No 4"}];
       $scope.suppliers = foos;
       $scope.selectedSupplier = {id:3,name:"No 3"};
  };

If you are comfortable with removing quotes, this could potentially be a viable solution for your situation.

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

Tips for accessing req.fields variables while utilizing Express-Formidable

For some reason, I am encountering difficulties when trying to access variables parsed within req.fields using Express-Formidable. Upon executing a console.log() of req.fields, the output is as follows: { 'registration[username]': '1', ...

When it comes to utilizing the method ".style.something" in JavaScript

Here is some javascript code that I am working with: function createDiv(id){ var temp = document.createElement('div'); temp.setAttribute("id", id); document.getElementsByTagName('body')[0].appendChild(temp); } c ...

Create a regular expression in Javascript that only matches strings that do not contain any periods

Struggling with setting up an express route for localhost:3000/test and utilizing regex to handle specific URL patterns. Need assistance combining regex with Express params functionality. router.get('/test/:path[\s^.]*$', function () { ...

Having trouble locating the namespace for angular in typescript version 1.5

I am using Angular 1.5 with TypeScript and have all the necessary configurations in my tsconfig.json file. However, when I run tslint, I encounter numerous errors in the project, one of which is: Cannot find namespace angular My tsconfig.json file looks ...

Access remote web page within bootstrap modal

Dealing with a recurring issue, I am trying to create a modal that opens content from a remote page populated by a MySql database. Custom styling is also required for the modal. Progress has been made, but now I'm stuck. Below is the current code: Ou ...

Customizing font size in React with Material UI: A comprehensive guide on adjusting the font size of the Select component

I'm currently working on a web application that utilizes React along with Material UI. My goal is to adjust the font size of the Select component. I've attempted to achieve this by utilizing the MenuProps property, as shown in the following code ...

Is it possible to use the AngularJS function with the <div> HTML element?

I am facing an issue with displaying a modal when clicking on a <div> element. The function assigned to show the modal by changing the CSS property 'display' from 'none' to 'block' works fine when attached to a button, b ...

The JSON file is not filling the options in the dropdown menu

procedure Add the objects from the dropdown into the dropdown menu. The Json file is located in root/ajax/.json and the working file is stored in root/.html. Problem: None of the objects from the JSON file are appearing in the dropdown menu. I attempted ...

Exploring Angular's Ng-Repeat for Nested Associations

My program is set up with the following connections: A :review contains many :comments, where each comment belongs to a :user who has a :username. However, when I try to display this information in my Angular view using the code below, it does not work as ...

Uninterrupted jQuery AJAX calls

I have a scenario where I need to periodically update an image on my view using ajax every 10 seconds. Any suggestions on how I can achieve this? Appreciate the help. ...

Using jQuery, is it possible to retrieve the product name and image dynamically?

I'm currently working on implementing an add to cart functionality using jQuery. When the add to cart button is clicked, the product name and image should be displayed. I can achieve this statically but I need help figuring out how to dynamically retr ...

What is the best way to eliminate the appended content within the tbody?

The code snippet below is functioning correctly. I am trying to retrieve the ID or Class of the appended data from the checkbox. However, when I use the following code $('.chk').click(function(){ console.log(cc);}), it does not work as expected. ...

Tips for changing the click event of a button with .on/off

My approach for attaching and detaching event handlers is through on()/off(). HTML: <div id='load' class="UnfiledContainer"> <button onclick="loaded()">Try it</button> <p id="demo"></p> </div> JS: ...

Why is the jQuery datepicker malfunctioning when nested within ng-repeat in AngularJS?

I am currently facing an issue with the jquery ui date picker in my AngularJS application. The date picker is functioning correctly outside of any ng-repeat loops, but it stops working when placed within one. <input type="text" class="form-control date ...

There seems to be an issue with Ajax functionality within the Webix framework

Exploring webix for the first time has been quite an interesting journey. I am carefully following the guidance provided in the getting started document to create my own webix program. By placing my code in an HTML page and two JSON files as instructed, he ...

What causes these queries to function separately but fail when combined?

I am facing an issue with combining 2 queries in my Firestore collection. These are the 2 examples that work: database .collection('servicebonnen') .where('medewerker', '==', 'CEES') and: database .collecti ...

Tips for assessing JSON response data from an AJAX form

I am struggling with how to properly structure a question, but I would like to explain my situation. I am using AJAX to send data and receiving JSON in return. Each value in the JSON response represents a status, and I need to test and react based on these ...

Location-based services: Updating the position of a Google Maps marker without refreshing the entire map interface

How can I update only the marker on a map when the device is in motion or has increased accuracy? I want to reload the map when the position changes, but only move the marker. Below is the code snippet that I currently have: if (navigator.geolocation) { ...

What could be causing React to throw an error?

Check out this React Component: GeneralInformation = React.createClass({ totalCaptialRaisedPanel: function() { var offeringInfo = this.props.company.data.offerings.data[0]; var percentageComplete = (offeringInfo.capital_raised / offer ...

What are the pros and cons of passing an imported object from a parent component to its children as props versus directly importing that object within the children components?

My current project involves a helper object known as TimeHelper, which is used for time-related tasks. This object is required in multiple components within the top-level parent component. I am contemplating whether it would be advantageous to import Time ...