Using AngularJS to dynamically update an array of objects in response to a selection change

I am facing a challenge with two dynamic object arrays: one for colors and one for buses. The main objective is to assign a color to each bus. I have used ng-repeat to create selects for each color, and employed ng-change to call the updatebus function, passing in the color id. However, I am encountering an issue where the color id always returns as undefined.

How can I effectively assign colors to buses using these two arrays? What mistake am I making in my approach?

In my attempt to resolve this issue, I referred to this answer: getting the ng-object selected with ng-change

Plunker

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8>
  <title>Example - combining two arrays</title>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js></script>
</head>
<body ng-app="selectExample">
  <script>
angular.module('selectExample', [])
  .controller('ExampleController', ['$scope', function($scope) {

    $scope.colors = [
      {name:'black', id:'a'},
      {name:'white', id:'b'},
      {name:'red', id:'c'},
      {name:'blue', id:'d'},
      {name:'yellow', id:'e'}
    ];

    $scope.buses = [
      {name:'bus 1', colorid:''},
      {name:'bus 2', colorid:''}
    ];

    $scope.theBus = $scope.buses[1]; // red

    $scope.updatebus = function(bus, id){
      //alert(id); // undefined
      $scope.theBus = bus;
      bus.cid = id;
    };
  }]);
</script>
<div ng-controller="ExampleController">

<p>
  Bus Color:
  <div ng-repeat="bus in buses">
  {{bus.name}} 
    <select ng-model="myColor" 
    ng-options="color.name for color in colors" 
    ng-change="updatebus(bus, color.id)">
      <option value="">-- choose color --</option>
    </select>
    <p>
  </div>
  <div>
    the bus "{{theBus.name}}" has color id "{{theBus.colorid}}"
  </div>

</div>
</body>
</html>

Answer №1

There were a couple of issues that needed to be addressed:

  • A typo was found in your code: bus.cid = id;
  • The expression used in ng-change seemed illogical: updatebus(bus, color.id). What exactly is color? There are multiple colors available.

One solution could be:

bus.colorid = id;
<select ng-model="myColor" 
ng-options="color.id as color.name for color in colors" 
ng-change="updatebus(bus, myColor)">

Check out the updated Plunkr here: http://plnkr.co/edit/571TY2dC8cmLSPA7AAIv?p=preview

Alternatively, you can directly bind your select to bus.colorid (this would be more efficient, especially if your buses already have initial color values):

<select ng-model="bus.colorid" 
ng-options="color.id as color.name for color in colors" 
ng-change="updatebus(bus)">
$scope.updatebus = function(bus){
  //alert(bus.name); // undefined
  $scope.theBus = bus;
};

Answer №2

To ensure full access to the selected color for each bus, it is recommended that you use the color of the bus from your ng-repeat as the ng-model of your select.

<select ng-model="bus.color" 
    ng-options="color.name for color in colors" 
    ng-change="updatebus(bus)">

All assignments should be done in the html bindings, with the ng-change remaining just for display purposes.

A few minor changes have been made to make everything work smoothly:

http://plnkr.co/edit/SoBUK61121VrqT31Jihj?p=preview

I hope this information proves helpful.

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

Is there a way to confine a draggable object's movement to a specific area?

Users have been granted the ability to input their characters onto the screen and manipulate each character's position. However, I only want users to move these characters within a specific square or rectangle area, limiting their placement options. ...

Troubleshooting Error in WebSocket with 'ws' Library in Node.js and Vue.js: Issue with RSV1 Flag Unset

I've come across a problem with WebSocket connections while working on my Node.js and Vue.js project. I've implemented the 'ws' library for WebSocket functionality, but I keep getting the error message "Invalid WebSocket frame: RSV1 mus ...

Vue3 is struggling to apply dynamic styling exclusively to certain buttons

Currently, I am diving into the world of vue and facing a challenge in styling buttons dynamically when clicked individually. These buttons serve as filters for a list of products, and my goal is to apply one style when the filter is 'on' and ano ...

Effectiveness of jquery for image swapping appears to be problematic

I'm having trouble getting the following code to work in Google Chrome. I believe it should be working, but for some reason it's not. Here is the code: <html> <head> <script type="text/javascript" src="js/jquery_1.7.1_ ...

JavaScript: Utilizing numbers to extend a sequence

My code is saved in a Google Sheets document and here is how it looks: ss = SpreadsheetApp.getActiveSpreadsheet(); function onOpen() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var menuEntries = [ {name: "10 Rows", functionName: "TenRows"}, ...

Display the value in Vue.js as a price format while maintaining it as an integer

I have created a Vue component called "formatted-number" which takes in an integer value (e.g. 1234) and currently displays it as a string (e.g. "12.34") to represent a price in a textfield, with the appropriate "," or "." based on the country. However, I ...

Python script using Selenium to scrape AngularJS elements by iterating through find_elements_by() function

When scraping real estate data, Selenium works wonders on sites generated with javascript. Finding the relevant information tags and looping over them is easy: driver.find_elements_by... However, when dealing with listings produced by AngularJS like on t ...

Flex RemoteObject: Reusing memory for arrays with identical values

When sending remote data from Zend_Amf to Flex, if two array properties on the object have the same data values, they will be deserialized at the remote end with the same memory storage. For example, in AS3: Snippet: [RemoteClass(alias="TestVO")] public ...

Potential dangers involved in sending HTML content through an AJAX request over a secure HTTPS connection

I am exploring the idea of dynamically loading HTML content, such as updating a Bootstrap modal dialog's contents using AJAX calls instead of refreshing the entire page. However, before I proceed, I want to understand the potential risks involved and ...

The Facebook SDK fails to activate in Internet Explorer

I am currently working on implementing a Facebook login using the JavaScript SDK. Everything is functioning correctly in most browsers, but I am experiencing issues with certain versions of Internet Explorer. The login functionality is not working on my l ...

Error message: The Modelviewer is unable to load the local file, displaying the message "Unauthorized to access local resource."

For my WebAR project, I am utilizing Google's ModelViewer. In my vue.js project, I have a component that loads the model using the <model-viewer> attribute. My goal is to set the src attribute of the model-viewer to the absolute path of the .gl ...

How can you send an error message from Flask and then process it in JavaScript following an AJAX request?

So I have successfully created a Python backend using Flask: @app.route('/test/') def test(): data = get_database_data(request.args.id) # Returns dict of data, or None if data is None: # What should be the next step here? re ...

Is it recommended to utilize an array for storing responses to multiple choice options a,b,c,d?

As someone new to C programming, I am eager to create a multiple-choice vocabulary practice program for my students. Instead of using 4 separate variables (a,b,c,d), I'm interested in using an array or exploring other efficient ways to store these cha ...

Socket.io in Express is already assigned to another address

I'm having trouble getting my app to connect with Socket.io via websockets. Each time I attempt to run this code snippet, I encounter the following error: Error: listen EADDRINUSE: address already in use :::3000 Despite checking for any other process ...

In C, utilize pointers to reverse an array

#include <stdio .h> #include <stdlib .h> int main(){ char text1 [N] ; char reverse [N] ; char* txtptr = text1 ; char* revtxtptr = reverse ; int N; printf (”\n Please enter any text: ”) ; scanf(”%s”, te ...

How come I can't capture discord.js promise rejections within event callbacks?

As I delve into creating a discord bot, I encountered an interesting problem. To simplify things, here is a snippet that encapsulates the issue at hand: const Discord = require('discord.js'); const client = new Discord.Client(); client.on(&apo ...

When I click the search button on my website, it automatically scrolls to a particular <img> or <a> tag

My objective is to have the page automatically scroll down to a specific image when I perform a search using the search bar. Here is the HTML code for the search bar and button: <form id="search-form" href="#test1" class="smoothscroll"> <inpu ...

What is the best way to insert an element into a JSON array at a specific index within a recurring section?

I need to include the element "delete:true" after each occurrence of "_rev" in the sample request provided below. Original Request: { "docs": [ { "_id": "123", "_rev": "1-7836", }, { "_i ...

Guide on updating an object with an array in MongoDB through a request

In my attempt to update an object that contains an array in Mongo DB, the current structure is as follows: {id: 'idString', propA: propA, arrayB: [{propC: propC}, {propC: propD}, {propC: propE}] My goal is to send a request to update it to the ...

Running into issues on Heroku with Node, Gulp, and Browserify: Module Not Found Error

My asset building process relies on Gulp. Specifically for Javascript, I have a task set up with Browserify to handle all code dependencies. While everything runs smoothly locally, deploying to Heroku results in a Gulp failure with the following error: 2 ...