What is the best way to save information from an ng-repeat loop into a variable before sending it to an API?

My goal is to store the selected value from ng-repeat in UI (user selection from dropdown) and assign it to a variable.


function saveSelection() {  
    console.log('inside function')
    var postToDatabase = [];     
    vm.newApplicant.values = [];
    angular.forEach(vm.newApplicant.selections, function (value, data) {
        vm.newApplicant.values.push({
            item: value.item
        });
    });
    
    var registerNewApplicant = { 
        values: vm.newApplicant.values,
    }
    
    postToDatabase.push(registerNewApplicant);
    console.log('Selection Saved');
}

Answer №1

When you have a multiple select option, the selected items will be stored in an array of objects.

This code snippet demonstrates how to store the selected data from a dropdown menu into the variable regNewStudent as an array of objects under the key ethnic. You can view and test the functionality on this plunker link

HTML

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74151a13011815065a1e0734455a415a0c">[email protected]</a>" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl as vm">

    <select ng-model="vm.newStudent.ethnicity" placeholder="Ethnicity" aria-label="Ethnicity" ng-model-options="{trackBy: '$value.code'}" multiple ng-options="opt as opt.name for opt in vm.listofEthnicity">
    </select>

{{vm.newStudent.ethnicity}}

<button ng-click="vm.save()">Save</button>
  </body>

</html>

CONTROLLER

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  var vm = this;
  var regNewStudent = { 
          ethnic: ''
      };

  vm.listofEthnicity = [ 
    { "code": 111, "name": "New Zealand European/Pākehā" }, 
    { "code": 121, "name": "British / Irish" }, 
    { "code": 122, "name": "Dutch" }, 
    { "code": 123, "name": "Greek" }
    ];

    vm.save = function() {
      regNewStudent = { 
          ethnic: vm.newStudent.ethnicity,
	  };
        // Since the postToApi factory is not available, I am just logging the data.
		console.log(regNewStudent);
        //postToApi.push(regNewStudent); //uncomment on your code.
    };

});

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

Utilizing the Squared² Symbol in the Jscript File Path for Execution

I am encountering an issue with launching applications on a corporate portal that are tied to a specific business group. The problem arises when trying to access a file path that includes a ² character. This software is widely used on over 3000 computers ...

Encountering issues with the hyperlink tag '<a>' in an HTML document

I've encountered an issue with the code on my HTML page: <body> <div align="center"> <a href="../index.html"> <img border="0" src="banner1.jpg" width="800" height="120" alt="Ecommerce Knowledge Base"> &l ...

Incorporate a unique identifier for dynamic elements

Is there a way to give generated divs the same name so I can markup them easily? $.getJSON("data/reviews.json", function(data){ for(var i=0; i<data.length; i++) { var review = sym.createChildSymbol("Template", "content"); review.$("title").html ...

Tips for resolving the setAttribute() function error message: "Argument of type 'boolean' is not assignable to parameter of type 'string'"

I am currently working on a function that dynamically updates the HTML aria-expanded attribute based on whether it is true or false. However, when I declare element as HTMLElement, I encounter an error stating Argument of type 'boolean' is not as ...

using a function as an argument in the map method within a React component

I have a challenge where I am trying to display blog posts retrieved from my database. However, for each item, I also need to execute a download image function. I attempted to include the function within the .map function but encountered some errors. I am ...

Is there a way to modify an existing job in Kue Node.js after it has been created?

Utilizing Kue, I am generating employment opportunities. jobs.create('myQueue', { 'title':'test', 'job_id': id ,'params': params } ) .delay(milliseconds) .removeOnComplete( true ) ...

How to hide the header on a specific page using Angular

Currently, I am working on an Angular project and my requirement is to hide the header block specifically on the login page. Despite attempting to hide the header on the login page, it seems that my efforts have been unsuccessful so far. Is there anyone wh ...

Javascript is handling the JSON Request flawlessly, however, when using Nodejs, an error is encountered with a status

I'm trying to fetch a simple JSON File in NodeJS. Using Javascript and jQuery, it functions perfectly: $(document).ready(function() { $.getJSON('https://www.younow.com/php/api/broadcast/info/curId=0/user=Peter', function(json) { if ...

When using the JavaScript .sort() method, any undefined value must always be considered as coming before any other value

I am working on sorting an array of objects based on multiple fields, typically around 3-4 fields. Some values within the objects may be undefined, and I need to ensure that these undefined values are considered as "earlier" in the sorting process, wheth ...

What is the best way to monitor AngularJS's $timeout using Jasmine?

I am attempting to monitor the use of $timeout in order to confirm that it has not been executed. In particular, my production code (shown below) utilizes $timeout as a function rather than an object: $timeout(function() { ... }) instead of $timeout.can ...

What is the most efficient method for executing multiple variable=function() and determining when all tasks have been finished?

I am facing the issue of having multiple variables that need to be calculated before being saved as a JSON file. These calculations are done using a function, but when run asynchronously, they end up undefined. After reading about promises, it seems like t ...

What could be the reason for the checkbox not being selected in a React component

I'm currently working on integrating an autocomplete feature with checkboxes. Learn more here https://i.stack.imgur.com/YtxSS.png However, when trying to use the same component in final-form, I'm facing issues with checking my options. Why is t ...

Navigating to a new URL using window.location.href will seamlessly embed the new page within

I am new to JavaScript and I am facing an issue with my AJAX function. The function is supposed to navigate to a new URL, but instead of loading the new page separately as if the user had typed the URL, it gets inserted inside the same div where the button ...

Is JavaScript's setTimeout 0 feature delaying the rendering of the page?

Based on information from this StackOverflow post The process of changing the DOM occurs synchronously, while rendering the DOM actually takes place after the JavaScript stack has cleared. Furthermore, according to this document from Google, a screen r ...

Enhance your data retrieval from XPATH using Javascript

Here is the layout of an HTML template I am working with: <div class="item"> <span class="light">Date</span> <a class="link" href="">2018</a> (4pop) </div> <div class="item"> <span class="light">From</sp ...

Harness the power of electrons with the simple push of a button - initiating program execution

Recently, I delved into Electron with the desire to create a small application for myself. This app would allow me to run different programs or games by simply clicking on a link. My goal is to have the program/game start automatically when I open the Ele ...

Creating dynamic cubes in Magento with interact.js within a .phtml template

I utilized the interact.js library to create this code snippet, which functions perfectly on Chrome, Firefox, and w3schools "Try it Yourself" platform (unfortunately not compatible with Edge and IE for unknown reasons). However, when I include this code wi ...

Reproducing a table row

Here is the table structure I am working with: <table id="customFields" class="table table-bordered table-hover additionalMargin alignment"> <thead> <tr> <th colspan="2"></th> <th>Some Title</ ...

Navigating through the elements of the DOM

Here is a function that deletes people from a list when you click on a certain part of the form: function ParticipantsDeleteClick(model, url) { for (i in model.Participants) { $("#delete" + i).click(function () { $.ajax({ url: url, ...

Can you explain the functionality of the NextSibling method?

I have a question about how the property NextSibling behaves when using the method getElementsByClassName(). Let me illustrate the issue with this code example: function Sibling() { var x = document.getElementsByClassName('firstClass')[0]; ...