Using AngularJS and Web API to generate a dropdown menu from a one-to-many relationship

I have two tables in my database: People and Payband. Let me simplify the relationship below:

dbo.People

PersonId : int (Primary Key)
FirstName : string
MiddleInitial: string
LastName : string
DateOfBirth: datetime
PaybandId : int (Foreign Key)

dbo.Paybands

Id : int (Primary Key)
Name : string

Currently, I have set up an ASP.NET Web API service for the backend and utilized HTML/CSS along with AngularJS for the frontend. Data retrieval, display, and editing are working smoothly. Here's a glimpse of my form layout:

https://i.sstatic.net/ct9zx.jpg

Although I can retrieve the current Payband value assigned to a person, I am facing a challenge in fetching all other Payband values and presenting them in an HTML dropdown for easy payband selection for any individual. Your assistance on how to achieve this would be highly appreciated. Thank you beforehand, and feel free to ask if you have any queries.

Additionally, here is my AngularJS controller code (note that I am currently hardcoding the person's ID for testing purposes):

angular
.module("personnelService")
.controller("PersonnelEditCtrl",
             PersonnelEditCtrl);

function PersonnelEditCtrl(personnelResource) {
var vm = this;
vm.person = {};
vm.message = '';

personnelResource.get({ id: 2 },
    function (data) {
        vm.person = data;
        vm.person.dob = new Date(vm.person.dob);
        vm.originalPerson = angular.copy(data);
    });

if (vm.person && vm.person.personId) {
    vm.title = "Edit: " + vm.person.firstName + " " + vm.person.lastName;
}
else {
    vm.title = "New Person";
}

vm.submit = function () {
    vm.message = '';
    if (vm.person.personId) {
        vm.person.$update({ id: vm.person.personId },
            function (data) {
                vm.message = '... Save Complete';
            })
    }
    else {
        vm.person.$save(
            function (data) {
                vm.originalPerson = angular.copy(data);
                vm.message = '... Save Complete';
            })
    }
};

vm.cancel = function (editForm) {
    editForm.$setPristine();
    vm.person = angular.copy(vm.originalPerson);
    vm.message = "";
};

}

Answer №1

To ensure that the list of paybands is properly displayed, it is essential to create an endpoint on the server dedicated to publishing this information. This can be achieved by setting up a controller named PaybandsController with a Get action result that fetches the list of Paybands from the database. By connecting your paybandResource to this controller and utilizing the query function, you can effectively display the data. As Yaser suggested, link the vm.paybands variable to the user interface.

function PersonnelEditCtrl(personnelResource, paybandResource, $filter) {
    var vm = this;
    vm.person = {};
    vm.message = '';
    vm.paybands = [];

    paybandResource.query(function(data) {
        vm.paybands = $filter('orderBy')(data, 'Name');
    });

 //.......

When it comes to the view:

<select 
   ng-model="person.paybandId"                 
   ng-options="payband.name for payband in paybands track by payband.id">
</select>

Answer №2

To display all paybands, you must first retrieve them and then fill them into the select element.

<select 
   ng-model="person.paybandId"                 
   ng-options="payband.name for payband in paybands">
</select>

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

Exploring data visualization and time zones with highcharts on a React platform

I am working on a chart component in React that is populated with data from an API. The array of objects I receive contains rows structured like this: Rows: [ { EffectiveTime: "06-Nov-2020 00:00:00", FieldName: "GEN_EXP", Re ...

Using the Github API in javascript, store an image as an image by saving its base64 Data URL

I have a base64 encoded Data URL of a webp image that looks like this: data:image/webp;base64,R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs= My goal is to push this image to GitHub using their API in the form of a webp image. To clarify, I want to achi ...

The validation process in reactive forms is experiencing some issues with efficiency

Trying to debug an issue with my reactive forms - the repeatPassword field doesn't update as expected. When entering information in the "password" field, then the "repeatPassword" field, and back to "password", the second entry is not flagged as inval ...

Is it better to utilize AngularJS $http service for making requests, or should I opt for jQuery AJAX if available

When working on my project, I rely on the angularjs framework and always enjoy utilizing the $http service for ajax calls. However, I have come across situations in the project where the UI is not directly impacted by the ajax call and angularjs bindings a ...

Tips for utilizing createTextNode in JSDOM

When attempting to create a UI test for an HTML element using Jasmine and jsdom, I encountered an issue. Within my component, I utilized the createTextNode function to populate the content of the DOM element. Unfortunately, during testing, the document.c ...

Identifying Changes in Form Values Using jQuery

I am facing a challenge with a dynamic form that needs to detect the field sequence properly. Below is my JavaScript file: var i = 1; $("a.add-line").click(function(){ $("div.items").append( $('<div>').attr('id',&ap ...

What is the best way to combine PHP and HTML within a JavaScript script?

I'm facing a challenge with integrating dynamically added elements and a populated drop down on my form. Is there a way to combine the two seamlessly? Below is the code snippet I'm using for dynamically adding and removing elements: $(docu ...

An approach to looping through arrays within an object in JavaScript

I have a JSON structure that consists of an array containing arrays, each holding dictionary elements. This data is retrieved from a function-based view. I am looking to iterate through all the elements and filter out arrays with empty dictionaries. data. ...

[Vue alert]: "Maximum" property or method is not declared in the instance but is being referenced during the rendering process

Here is my custom Vue component: Vue.component("product-list", { props: ["products", "maximum-price"], template: ` <div> <div class="row d-flex mb-3 align-items-center p-3 rounded-3 animate__animate ...

Verify all inputs are complete in the FullScreenForm

I have been working on implementing a form from this website: http://tympanus.net/Development/FullscreenForm/ My main objective is to validate each input when the form is submitted and display any errors that may arise. To achieve this, I have already se ...

Having trouble executing "npm install" following the clone from GitHub in React

After cloning a repository from GitHub, I attempted to run "npm install" but encountered the following error: https://i.sstatic.net/QM4RZ.png Since the project is still in development, should I install or add anything else to successfully run it? ...

Can Browserify be used with AngularJS to bundle directive templateUrls using relative paths?

Currently, I am developing a web application using AngularJS and Browserify to bundle my JavaScript files into a single package for use on the webpage. My project structure looks something like this: app |-index.html |-index.js |-bundle.js |-components ...

Encase Regex Matches from the Inner Text of an Element in HTML Tags

I have a div element with some content inside. I am trying to use regular expressions to target specific parts of the text, wrap them in span elements with a class attribute "highlight-yellow" and add a custom attribute called my-custom-attribute="hello". ...

A customizable and adaptable Tetris-inspired CSS design perfect for any screen size

If we imagine having a block like this: <div class="block"></div> There are different sizes of the block: <div class="block b1x1"></div> <div class="block b2x1"></div> <div class="block b1x2"></div> For i ...

Various JSON Tag values occurring more than once

Upon receiving a JSON Object in HTML, I am passing it to a JavaScript function defined below. The issue arises when the same folderName appears repeatedly on the HTML page. JSON Object: { "folderName": "arjunram-test", "objects": [ { ...

What could be the reason for this Javascript code not functioning as intended, failing to generate a random number between 1 and 3 when I click on any of the buttons

Could someone help me with generating a random number between 1 and 3 each time I click on one of the buttons (rock, paper, scissors)? I am new to programming and not sure what I'm doing wrong. <!doctype html> <html lang="en"> <head& ...

Angular.js is a great tool for showing PDF files on a

I am facing a challenge while trying to incorporate a PDF file into my Angular.js website. The PDF is stored as a blob in a MySQL database and I want to display it as one of the partial views that appear on the main page when a link is clicked. Unfortuna ...

Navigating with AngularJS in an ExpressJS Server

I currently have a setup consisting of an AngularJS app running on a NodeJS server with ExpressJS. I am serving the Angular app as static files using the following code: app.use(express.static(__dirname + '/app')); One issue I encountered is th ...

Security vulnerability found in version 1.2.9 due to insecure local URL

I am facing an issue with the code below: <span ng-include="getHeaderTemplate()"></span> The function getHeaderTemplate() is returning "templates/header/prospection.html" However, I am encountering the following error message: Error: [$sce ...

Emulate sequelize using Jest in combination with sequelize-mock

In my latest project, I have been implementing TDD as the primary methodology along with integration tests. One of the tasks at hand is to retrieve all users from the database. //controller.js const UserService = require('../services/user'); mod ...