Upload an array of choices to the server by utilizing ng-model

I have almost resolved my issue, but now I need help with sending the data to the server.

In my current situation, there is a form that includes employee details and projects for that employee (which can be multiple).

When the user wants to add projects, they need to click on "Add Projects". This action will generate a dropdown on the page containing a list of available projects.

The user can select any number of projects. Once they have selected their desired projects (let's say 5), they can click submit to post the data to the server.

I would like all the selections from the dropdown lists to be stored in an array and then sent to the save function.

Here is the HTML Code:

<div>
                        <div ng-controller="AlertDemoCtrl">
                            <alert ng-repeat="alert in alerts" type="alert.type" close="closeAlert($index)" ng-model="ProjectId[item]">
                        <ul style="list-style-type: none; margin-left: 0px;">
                            <li >
                                <select>
                                    <option value="">-- Choose a Project --</option>
                                    <option ng-repeat="item in items" value="item.ProjectId">{{item.ProjectName}}</option>
                                </select>
                                <button type="button" ng-click="closeAlert($index)"><img src="delete.png" alt="Remove" style="height:20px; width:20px;" /></button>
                            </li>
                        </ul>
                    </alert>
                            <button class='btn' type='button' ng-click="addAlert()">Add Projects</button>
                        </div>
                    </div>

The 'alert' custom directive adds new dropdown lists to the form. Remember to create a controller for adding new employee data.

var CreateCtrlEmp = function ($scope, $location, SampleEmp, SampleProj, SampleDes, sharedValues) {
$scope.items = SampleProj.query({ q: $scope.query });
$scope.itemsd = SampleDes.query({ q: $scope.query });
alert("Entered the saving function");
$scope.save = function () {
    $scope.item.ProjectId = [];
    SampleEmp.save($scope.item);
    $location.path('/emp');
};};

Your help would be greatly appreciated.

Thanks a lot!

Tushar Sharma

Answer №1

Do you need to send this specific data structure to the server?

{
    employee: {
        name: "John Doe",
        projects[{
           name: "React Website"
        }]
    }
}

To achieve this, you can implement a submit handler in the controller:

function EmployeeCtrl($scope) {
    $scope.employee = {projects:[]};  // Initialize the data structure
    $scope.submit = function() {
      console.info($scope.employee);
      // Convert the employee data structure to a string and POST it to the server
      postToServer(JSON.stringify(angular.copy($scope.employee)));
    }
}

The use of angular.copy ensures removal of the $$hashKey property on the project items.

https://github.com/angular/angular.js/issues/1875

Your form should resemble this:

<form ng-submit="submit()">
    <input ng-model="employee.name">
    <div ng-repeat="project in employee.projects">
        <input ng-model="project.name">
    </div>
    <button type="submit">Save</button>
</form>

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

Discovering the technique to unearth a specific value within an array nested within another array

I am encountering an issue with finding a value in one array inside another array and utilizing the resulting value to update the state using setState(). Here is the initial state: this.state = { initialStudents:[ {name:"str1",tags;["str","s ...

Incorporating Angular into the script code of the extension content

I am looking to customize text fields on a website using a chrome-extension. However, the website is built with Angular, so I need to modify the text fields using Angular code. To incorporate Angular in my extension's scope, I am attempting to declar ...

What is the best way to find the most commonly used category for a product in a MongoDB collection?

I've been diving into MongoDB and encountered a challenge with my current task. I'm trying to figure out how to determine the most frequently used category in a collection. According to this JSON, the most used category is CIES. My goal is to dis ...

Tips on converting deeply nested JSON into an excel file using Node.js

I am attempting to convert the JSON data below into an Excel file using XLSX. Although it successfully converts my JSON to Excel, I encountered an issue where the nested array of dailyPointsArray appears blank after conversion. Code Attempted const XLSX ...

AngularJS - Introducing blurred delay

Here is the code snippet I am working with: <div class="staff"> <input ng-model="user" ng-focus="isFocused = true;" ng-blur="isFocused = false;/> <div class="matches" ng-if="isFocused"> <div ...

http-proxy-middleware - serving static content

I am currently working on integrating my static landing page with an express.js app (using react.js for the single page application). For my landing page, I have set up a proxy using http-proxy-middleware. Here is what my server.js file for the static pag ...

Enhance Website Speed by Storing PHP Array on Server?

Is there a way to optimize the page load time by storing a PHP array on the server instead of parsing it from a CSV file every time the page is reloaded? The CSV file only updates once an hour, so constantly processing 100k+ elements for each user seems un ...

Attempting to showcase the information in my customized SharePoint Online list through a Web Part Page utilizing AngularJS

<script> //AngularJS Code goes here var appVar = angular.module('listApp', ['ngRoute']); appVar.controller("controller1", function($scope){}); function FetchEmployeeData($scope, EmployeeList){ var reque ...

Expanding the Number of Arguments Sent to a Callback Function

I have a scenario where I am using a method that sends a POST request and then triggers a specific callback function to manage the response: myService.verify(id, verificationCallback); function verificationCallback(err, response) { ... } My query is two ...

Unable to import local npm package due to an error

We are in the process of migrating multiple websites, each with its own project, to Vue.js. As we transfer files over and bundle them using Webpack, we have encountered a need to consolidate similar components and core JavaScript files into a shared librar ...

Sending a user to an external website through an XML response

In my current project, I am utilizing jQuery to fetch a PHP file. The PHP file executes a cURL request to an external website in order to obtain information for a payment request. The external site responds with XML data structured as follows: <Request ...

Unable to save cookies using AngularJs

Currently, I am immersed in a small project utilizing AngularJs. The main objective of this project is to save a user's username and password within browser cookies. Here is my snippet from app.js where you can observe ngCookies being injected as a d ...

Angular 1.3.10 encountered error: [$injector:modulerr] - Uncaught Exception

The application currently has limited content, resulting in this basic error. The use of ui-router is causing the issue. Here are the code snippets from different files: app.module.js: 'use strict'; angular .module('app', app); ...

text field remaining populated

I have a form where the input fields clear when they are clicked on. It works well on most pages, but there is a specific type of page where it is not functioning properly due to the presence of another javascript running. - issue observed // On this pa ...

What steps should I take to address the issue of the document not being defined?

I encountered an error that I initially thought was related to node.js, but now I'm not entirely sure. How can I go about resolving this issue? [Running] node "c:\Users\Lenovo\Desktop\projectjs\index.js" c:\User ...

Using angularjs to include content from other files is known as

As I delve into the concept of creating directives in AngularJS, I am faced with the imminent end of Angular 1.x and the rise of Angular 2.x. The shift seems daunting, but I am determined to bridge this gap seamlessly. In my quest for clarity, I stumbled ...

Leveraging the useEffect hook to make multiple API calls in ReactJS

I have a useEffect function in my react component where I am calling the API videoGridState. The issue I am facing is that the API is being called twice; once when the page initially reloads and again when the count changes. I want it to be called only onc ...

Warning: React has detected that a non-boolean value of `true` was received for the attribute `my-optional-property`

source code import React from "react"; import { Button, ButtonProps } from "@material-ui/core"; interface MyButtonProps extends ButtonProps { "aria-label": string; "my-optional-property"?: boolean; } function MyCustomButton(props: MyButtonProps) { ...

Verify the MAC address as the user types

I need to verify a form field for MAC Addresses and have implemented the following code that does the job. $('body').on('keyup', '#macAddess', function(e){ var e = $(this).val(); var r = /([a-f0-9]{2})([a-f0-9]{2})/i, ...

Animation triggered by scrolling is not functioning/displaying div

I'm attempting to make a div fade up when it enters the viewport by using the library found at https://github.com/michalsnik/aos Unfortunately, all that seems to happen is that the div gets hidden. In the head section of my HTML file, I've refe ...