How to populate a dropdown menu in AngularJS with ng-model bound list items

Currently facing a challenge with angularjs. Here is the scenario:

I have a Game entity and a Team entity. A Game can have multiple Team objects (ManyToMany Relationship).

In my frontend application, I need to add a new Game with optional Teams. For the Teams, I am using two dropdown menus (one for each team).

However, I am struggling to assign the correct values to the ng-model.

I attempted something like this, but it doesn't seem to be right:

<select class="form-control" ng-options="team.teamname for team in teams 
track by team.id" ng-model="game.teams[0]">
  <option value="" selected>-- No Team --</option>
</select>

<select class="form-control" ng-options="team.teamname for team in teams 
track by team.id" ng-model="game.teams[1]">
  <option value="" selected>-- No Team --</option>
</select>

Upon clicking the save button, I encounter an error message "400: Unable to process JSON":

Possibly unhandled rejection: {"data":{"code":400,"message":"Unable to process JSON"},"status":400,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","data":{"teams":{"0":{"id":1,"games":[{"id":1,"date":20180810}],"teamname":"BVB"},"1":{"id":2,"games":[{"id":1,"date":20180810}],"teamname":"FCB"}},"date":"20180810"},"url":"/api/games","headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":"Bad Request"}

Creating the two Teams for a Game with Postman works fine:

{
    "date": 20180810,
    "teams": [{"id": 1}, {"id": 2}]
}

Desired Output:

{
  "id": 1,
  "date": 20180810,
  "teams": [
      {
          "id": 1,
          "games": [
              {
                  "id": 1,
                  "date": 20180810
              }
          ],
          "teamname": "BVB"
      },
      {
          "id": 2,
          "games": [
              {
                  "id": 1,
                  "date": 20180810
              }
          ],
          "teamname": "FCB"
      }
  ]
}

Any suggestions on how to correctly set the ng-model (Game) with the values from the dropdown menus? Thank you.

I have included a screenshot of the desired form: https://i.sstatic.net/8DA44.png

Answer №1

It seems that there is a discrepancy between the data sent from Postman and the data sent from your Angular form.

{
    "date": 20180810,
    "teams": [{"id": 1}, {"id": 2}]
}

The data structure being sent from your Angular form is different:

{
    "date": "20180810",
    "teams": {
        "0": {
            "id": 1,
            "games": [
                {
                    "id": 1,
                    "date": 20180810
                }
            ],
            "teamname": "BVB"
        },
        "1": {
            "id": 2,
            "games": [
                {
                    "id": 1,
                    "date": 20180810
                }
            ],
            "teamname": "FCB"
        }
    }
}

While the date field matches, the teams structure differs - an object in the form instead of an array expected by the backend. There are also extra details like games and teamname, which may or may not be problematic for the backend system.

In most cases, such issues with AngularJS arise in the controller rather than the HTML template. Ensure that you have initialized scope.game.teams properly as an empty array in your controller:

scope.game = {
    date: 'something',
    teams: []
};

The problem likely stems from improper initialization of scope.game.teams, causing ng-model to set it as an object automatically.

Answer №2

It seems like you're interested in incorporating multiple teams for each game using a checklist model. I recommend checking out this resource: . This will allow you to send the server a list of games associated with each team.

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

merge a multidimensional array to create a dictionary object organized by keys

In my quest to construct a pricing structure for a product based on its color, size, and material, I have been grappling with the implementation process. Currently, I am maintaining a single JSON object that contains all possible options and attempting to ...

What is the best method for storing the item count in an active InfiniteQuery in React-Query?

Currently, I have implemented the @tanstack/react-query library in my React application to display a paginated list of items. When I make a request to GET /api/items?page=0, it retrieves data structured like this: { page: 0, pageSize: 20, total ...

AngularJS and Handlebars (npm)

Is it possible for angularJS to function as a substitute for the "view engine" in nodeJS? I am seeking insights on the optimal method to use. (Do MEAN Stack developers utilize view engines? Or do they prefer using res.sendFile along with tools like ui-ro ...

When you hover over the page, the content shifts to reveal a hidden div

Trying to figure out how to show additional content when a photo is hovered over without shifting the rest of the page's content placement? Looking for alternative solutions rather than using margin-top: -22%. Here's a link to the website in que ...

Can the key in a WeakMap be altered when setting an item within it?

When working with JavaScript, is it possible for setting an item in a WeakMap to change the object used as the key? I'm curious about this because if I were to create a WeakMap, my approach might involve using a Symbol on the key and then utilizing t ...

A guide to toggling SVG elements with AngularJS

Is it possible to toggle between two different svg images using the ng-include directive? For example, I currently have the following code snippet: <i class="indicator oppcicon {{domain.show_requests ? 'icon-chevron-down' : 'icon-chevro ...

Activate the stripe button after successful bootstrap validation

My goal was to implement BootstrapValidator for validation on a couple of fields and enable the Stripe button only when both fields are valid. Currently, the button is enabled once any of the fields pass validation. The challenge lies in ensuring that the ...

Squarespace as a Platform for d3.js Visualizations

Recently, I stumbled upon two blog posts (1, 2) that discuss implementing d3.js visualizations on Squarespace. Intrigued, I decided to try uploading an interactive network visualization to my own Squarespace site by following the instructions in both posts ...

Iterate over JSON dates in JavaScript

Trying to utilize JavaScript in looping through a JSON file containing time periods (start date/time and end date/time) to determine if the current date/time falls within any of these periods. The provided code doesn't seem to be working as expected. ...

Unlock the power of timers in AngularJSUnleash

I am currently developing a web application When the button is clicked, there is an insert query that should execute. If it takes longer than 15 seconds to insert, a message should appear in an alert stating that the internet connection is slow and to ple ...

Searching MongoDB Arrays by Date Filter

This is the operator Schema in my code: const operatorSchema = new Schema({ operatorName: { type: String }, users:[{ email:String, payment:Number, paymentsData: Date, product: String, }], }); I ...

Is it possible to remove the "getContext" property from the HTML5 Canvas element using a script?

Visit the HTML5 conformance test suite to find a test for the prototype of HTMLCanvasElement. While this test fails for Safari and Firefox, it passes for Opera on Windows 7. The script within the test attempts to delete the getContext property of HTMLCan ...

Developing a high-performing vertex shader in WebGL2 for early frame rendering

Filtering Instances in the Vertex Shader In my webGL2 project, I am utilizing instanced geometry to render content. Each instance contains a color component with varying alpha values, some of which may be zero. Instead of passing instances with zero alph ...

Utilize Jquery to insert the text into the input or textarea field

<div class="ctrlHolder"> <label for="" id="name.label">Name</label> <input name="name" id="name" type="text" class="textInput small" /> <p class="formHint">Please enter the name of the item you are submitting</p> </di ...

Use Angular to send an array to a Django view by utilizing the $http.post method

I am trying to make a post request to a django view with the following code: $http({ method: "post", url: "/enterprises/vouchers/_send", data: { group_id: group_id, group_student_ids: [1, 2, 3, 4] } ...

Incorporating sweetalert2 with the latest Bootstrap 4 framework

I am currently utilizing sweetAlert2 and attempting to integrate bootstrap 4 for button styling by implementing the following properties: buttonsStyling: false, confirmButtonClass: 'btn btn-primary btn-lg', cancelButtonClass: 'btn btn-lg&ap ...

`The functionalities of classList.add and classList.remove aren't behaving as anticipated.`

I'm currently working on a list of items (ul, li) that have a class applied to them which adds a left border and bold highlight when clicked. My goal is to reset the style of the previously clicked item back to its original state when a new item is c ...

Use JavaScript to gather various data forms and convert them into JSON format before transmitting them to PHP through AJAX

My understanding of JSON might be a bit off because I haven't come across many resources that discuss posting form data via JSON/AJAX to PHP. I often see jQuery being used in examples, but I have yet to delve into it as I've been advised to firs ...

Guide to importing images (.svg, .png) into a React component

I'm currently facing an issue trying to upload an image file in one of my React components using webpack. My project is already set up with web pack. Below is the code snippet for the component: import Diamond from '../../assets/linux_logo.jpg& ...

What method can we use to verify if an object falls within a specified date range when filtering?

Looking to determine if the current filter object falls within a specific date range and return a boolean value based on that condition. However, the code provided always returns the data. Can anyone spot the error in the implementation or suggest a better ...