Choosing an item in an AngularJS select directive from an external origin

I'm currently working on developing a form using Angular JS for editing venue details such as address and city.

The backend system is powered by Django and offers a REST API (Django Rest Framework) which I am interfacing with through Restangular services. This setup is functioning smoothly.

For most form elements, the process is straightforward. I have a venue object and populate the fields like this:

<input type="text" ng-model="venue.street">

However, each venue object has a category associated with it, which in Django is represented as a foreign key referencing a category object:

category = models.ForeignKey(Category)

When retrieving a venue from the REST API, the category is identified by the pk/id of the category object. For example:

{
    "id": 14,
    "name": "test place",
    "slug": "test-place",
    "country": "Ireland",
    "city": "Dublin",
    [...etc...]
    "category": 1
},

There is also a separate REST endpoint that provides information about the categories:

[
{
    "id": 1,
    "name": "Rock"
},
{
    "id": 2,
    "name": "Classic"
},
{
    "id": 3,
    "name": "Jazz"
}
]

My current challenge lies in setting up a dropdown menu in the form to display category names while submitting only the category ID to the backend. Additionally, I need to pre-select the venue's existing category when the form is initially displayed.

As a newcomer to Angular, my understanding is that Angular fills a select directive with references to the objects themselves rather than simple IDs.

Currently, I have this code snippet:

<select ng-model="venue.category" ng-options="category.name for category in categories track by category.id"></select>

Unfortunately, this approach doesn't work because although both venue.category and category.id are numbers, they are not the same object.

I believe there is likely a straightforward solution that I am missing and would appreciate any guidance you can offer.

Thank you!

Answer №1

When using Track by, you are indicating that two different objects should be considered equal for the select box. However, in this case, you simply want the model to be the id itself. Angular provides support for this specific scenario.

http://jsfiddle.net/XLpFN/

For instance:

<select ng-model="venue.category" ng-options="category.id as category.name for category in categories"></select>

$scope.categories = [ 
    {"id": 1, "name": "Rock"}, 
    {"id": 2, "name": "Classic"}, 
    {"id": 3, "name": "Jazz"}
];

$scope.venue =  {
    "id": 14,
    "name": "test place",
    "slug": "test-place",
    "country": "Ireland",
    "city": "Dublin",
    "category": 2
};

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

Experiencing difficulty accessing Admin Panel in Django due to utilization of Custom User Model

After creating a custom user model that overrides the default AUTH_MODEL in settings.py, I encountered an issue while trying to login on the admin panel using python manage.py createsuperuser. The error message displayed by the admin was: Please enter th ...

Discovering the method to retrieve the values from 2 dropdown lists that are populated by a JavaScript function

I have a pair of dropdown lists in a JSP file labeled 'speciality' and 'super_speciality'. Clicking on an option in the 'speciality' dropdown list dynamically populates options in the 'super_speciality' dropdown list ...

Issue with spacing when assigning a JavaScript array variable to a value within input tags during a loop

Having some trouble with JavaScript code where the value is not passing in its entirety if there are spaces between the words. How can I make sure the full string or array object gets passed into the input tag's value? This is how I am trying to assi ...

Passing variables on form submission in Django: A simple guide

I am working with a django 1.6.11 form (views.py): def posneg_nlp(request): sys_project_name = request.GET.get('project', 'graph') # everything works fine here, it can get the correct project value success = False monitoring_words = &a ...

Creating a rhombus or parallelogram on a canvas can be easily achieved by following these simple

I'm new to working with the canvas element and I want to create some shapes on it. Can someone provide me with guidance on how to draw a Rhombus or Parallelogram on a canvas? Something similar to what is shown in this image: https://i.stack.imgur.c ...

hover over the picture with your cursor

Struggling with jquery and css, could use some assistance :) Check out my html code below: <html> <head> //myscripts <script> $(document).ready(function(){ $(".cover").hover(function(){ //the function i need to write } ...

Angular - There is already an ongoing $apply process in place

I am seeking advice on an angular issue: Encountered the same error as outlined here: https://github.com/angular-ui/bootstrap/issues/516. Does this error ("$apply already in progress") pose a risk to my app? My tests indicate that the error does not nega ...

Please enter a number using the "+" sign and a decimal point

In my input field, I have specified: <input type="number" step="0.01"> I expect all of these input values to produce the following outputs: 2.00 => 2.00 2,00 => 2.00 +2,00 => 2.00 However, when entering the value "+2.00", it fail ...

Designing a dynamic presentation with varying intervals between slides

I am working on a jQuery slideshow that smoothly transitions between different <div> elements. In the current code, the slides change every 5 seconds. Is there a way to modify this so I can specify custom durations for displaying each slide? Here i ...

Merging two identical Django objects in uinque way

Is it possible to combine two or more objects of the same model into one with the total values of all fields? For example, like using Author.objects.annotate(Sum('book__pages')) but for all fields in the model. Object 1 - {'user':2, & ...

React function failing to utilize the latest state

I'm facing an issue with my handleKeyUp function where it doesn't seem to recognize the updated state value for playingTrackInd. Even though I update the state using setPlayingTrackInd, the function always reads playingTrackInd as -1. It's p ...

Utilizing OrbitControls with SVGRenderer displays a pair of SVG elements positioned at opposite ends

In my project, I have created two scenes and two renderers. One scene is for a simple 3D mesh sphere, while the other is for an SVG circle. The SVG scene is positioned on top of the Mesh scene, acting as an overlay. Both the sphere and the circle are place ...

Leverage jQuery to organize and categorize JSON information received through an Ajax call

I have retrieved the following array from a MySQL database using PDO: [{ "tbl":"1", "orid":"915", "date":"2021-12-30 12:46:48", "flag":0 }, { "tbl":"2", "orid":"914", "date":"2021-12-30 12:46:21", "flag ...

Is it necessary to download all npm packages when starting a new project?

I recently started learning about npm packages and node. I noticed that when installing packages, they create numerous folders in the "node modules" directory. This got me thinking - when starting a new project, do I need to re-install all these packages ...

AngularJS Dilemma: Virtual Machine Data Set but No Rendering in Sight

Below is the AngularJS controller code written in Typescript: /// <reference path='../../definitions.d.ts' /> module baseApp.viewControls.products { export interface IProductsScope extends IAppScope { vm: { product ...

Exploring the intricacies of React Router parameters

I have been facing some issues with my routing setup. Specifically, I have a static route called list and a dynamic route called user/:id. The problem arises when navigating between these two pages. (1) Whenever I navigate to the list route from the user/: ...

What causes the left click to not trigger in Kendo's Angular Charts?

My homepage features a simple bar chart that displays correctly, but I am having trouble capturing the left click event (the right click works fine). This is an example of code from my template: <kendo-chart *ngIf="(dataExists | async)" [ ...

An error of TypeError is being encountered in AngularJS

Hello, I am new to creating mobile apps with Ionic and Angular. Currently, I have a simple login form and a corresponding login button that triggers a controller. Here is the code snippet for the controller: angular.module('starter.controllers', ...

Error: It seems like there was a problem with the injector and the module could not be

Currently, I am encountering an issue with the code below. Whenever I try to run it, I receive the following error: Uncaught Error: [$injector:nomod]. Even though the module name is correct, I am unsure of why this error is occurring. I have double-checked ...

Tips for updating iframe source without refreshing the iframe?

I am facing an issue with two frames where I need to copy the content from the first frame (myframe) to the second frame (myframe2) using JavaScript. The challenge is that when I set the "src" attribute for myframe2, it causes a reload of FrameSecond. Is ...