Send key-value pairs to the function using ng-model

I am currently working on a functionality that involves extracting an object from json and displaying its key-value pairs using 'ng-repeat' in AngularJS. The form includes checkboxes where the value can be either true or false, determining if they should be checked or not.

<form class="form-horizontal">
  <div class="form-group form-group__bordered"
       ng-repeat="(key, value) in listOfNotificationTypes">

    <label for="inputEmail3">{{ key | trimkey }}</label>

    <div class="checkbox-wrapper">
        <input type="checkbox" class="checkbox" ng-checked="{{value}}">
    </div>
 </div>

 <div class="form-group">
    <div class="col-12 clearfix">
        <a href="#" class="btn"
            ng-click="updateNotificationSettings()">
         SAVE
        </a>
    </div>
 </div>
</form>

While everything is functioning correctly, I am now looking to capture any changes made to the key-value pairs when the 'SAVE' button is clicked and send them through another function. I need to ensure that the data is formatted correctly in JSON, like this:

{
   "key1":"value1",
   "key2":"value2",
   "key3":"value3",
    ...
  }

I believe utilizing 'ng-model' will allow me to capture the necessary data, but I am uncertain about the proper implementation. Any guidance on how to achieve this would be greatly appreciated.

Answer №1

In order to work with your specific type of object, you'll need to utilize the input in this manner.

<input type="checkbox" class="checkbox" ng-model="listOfNotificationTypes[key]">

Check out this plunker for a demonstration of how it's implemented.

Important Notes: A quick tip for future reference: you may eventually need to convert that object into a list of objects like this

[
   {key: "key1", value: false},
   {key: "key2", value: true},
   {key: "key3", value: false}
  ];

If that scenario arises, the frontend code will appear as follows

<div class="form-group form-group__bordered" ng-repeat="notification in listOfNotificationTypes">
 <label for="inputEmail3">{{ notification.key }}</label>
  <div class="checkbox-wrapper">
    <input type="checkbox" class="checkbox" ng-model="notification.value">
  </div>
</div>

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

Retrieving data in JSON format from an API and converting it into a more usable JSON format using Flask

How can I convert data from JSON format into a web application using Flask to populate values in HTML? Here is the code in spec_player.html: {% for p in posts: %} <p>{{p.first_name}}</p> {% endfor %} This method works (main.py): posts = ...

Error message: "An unfamiliar service found in the testing scenario for Angular using ES6 modules

I need to create a karma-jasmine test case for a controller (-> class AddUserController @$inject = ['$scope', '$http', '$state', 'UserFactory'] constructor: (@$scope, @$http, @$state, UserFactory) -> ...

What's the best way to organize a list while implementing List Rendering in VueJS?

Currently, I am working on List Rendering in Vue2. The list is rendering correctly, but it appears ordered based on the data arrangement in the array. For better organization, I need to sort each item alphabetically by title. However, I am facing difficult ...

Redirect link depending on JSON callback information

I experimented with utilizing JavaScript to automatically redirect website visitors based on their country. The code snippet below demonstrates how the visitor's IP is checked to determine their country, such as CN for China, and then redirects them ...

Having trouble with Autocomplete not entering cities into the form?

While experimenting with Google's API, I have encountered confusion regarding why cities like Staten Island, Brooklyn, Queens, and various others are not being placed into the form like other cities. According to Google's API, "locality" is suppo ...

Removing data from the controller with JQUERY AJAX in a Spring MVC application

Could someone assist me with this issue? I am trying to implement ajax and sweetalert.js using the following repository: So far, everything is working well when I use onclick = "" to call my function. However, I need guidance on how to properly utilize th ...

Developing an intricate nesting structure for an object

this is my code snippet: "book" => {b:{o:{o:k:{'end':true} could someone please provide an explanation or a helpful link for this? const ENDS_HERE = '__ENDS_HERE' class Trie { constructor() { this.node = {}; } insert(w ...

The Mongoose connection pool has been shut down

I am currently working on a web application that retrieves data from a Mongo database. I have set up 2 cron jobs using Heroku scheduler to run daily and perform tasks on a remote database. The issue arises when these jobs need to conclude and close the con ...

Implementing conditional UI-views in AngularJS: A step-by-step guide

I would like to have a Home page load by default with a signup/login option, without displaying a header or footer on this particular page. After the user successfully logs in, I want to redirect them to the loggedIn.html page, which will include a fixed h ...

a guide on showcasing a table according to a specific column's data (CSV Path)

I currently have a table structured like this: File Name File path MyFile1.csv D:\tmp\MyFile1.csv MyFile2.csv D:\tmp\MyFile1.csv As of now, my primary table is displayed as shown below: <div class="panel-body table-res ...

Craft dynamic SVG components using TypeScript

Looking to generate a correctly formatted SVG element using TypeScript: createSVGElement(tag) { return document.createElementNS("http://www.w3.org/2000/svg", tag); } Encountering an issue with tslint: Error message: 'Forbidden http url in str ...

What is the process for uploading files with just node.js?

My dilemma involves a webpage featuring a form with a file input field. Upon submitting the form, I wish for the server to write the file on the server side. Despite numerous attempts to upload various test images using this form, each results in a plain ...

Tips for adjusting the animation position in Off-Canvas Menu Effects

I am currently utilizing the wave menu effect from OffCanvasMenuEffects. You can view this menu in action below: ... // CSS code snippets here <link rel="stylesheet" type="text/css" href="https://tympanus.net/Development/OffCanvasMenuEffects/fonts/f ...

What is the correct way to adjust the style.top attribute of an element using JavaScript?

In order to correct a JavaScript source code, I need to adjust the style.top property of a div element based on an integer parameter from a function called index. Here is the current implementation: div.style.top = (index * 22 + 2)+"px"; However, for lar ...

Serializing list objects with Jackson in Spring Boot

In my Spring Boot ReST controller, I am returning a List of "Personnel" objects. The output is mostly fine, but there is an issue that I need to address. Each Personnel object contains a nested object called PersonnelType. When serializing the first Perso ...

Instructions for adding username/password authentication using Express ntlm

Attempting to set up username and password authentication using Express-ntlm. I've included the following code as middleware: app.use( ntlm({ domain: '<domainname>', domaincontroller: '<ldap url>', })); I haven't ...

What is the best way to delete a jQuery.bind event handler that has been created for an event

I have a div and I need to assign two scroll functions to it, but I also want to remove one of them after a certain condition is met. <div id="div1" class="mydivs"> something </div> <div id="div2">Some crap here</div> <script&g ...

JQuery AJAX not retrieving data after $.post request

I am currently facing a challenge with a specific JQuery $.post request to a PHP-based processor. To troubleshoot, I set up a test page containing the following code: It's important to note that this is hosted on a subdomain, but there are no cross-d ...

What is the best way to utilize MongoDB aggregate in this particular scenario?

How can I optimize this mongoose query to improve performance and reduce size for production? const currentYear = (new Date).getFullYear() const usedCars = await CarModel.find({ ModelYear: {$lte: currentYear - 1} }).limit(10) const recentCars = await Car ...

Issue: Unable to create the restangular module because: the variable '_' is not defined

Upon integrating Restangular into an existing website, I encountered a JavaScript error that stated: Failed to instantiate module restangular due to: '_' is undefined I'm unsure of what this means. Can anyone clarify why '_' is ...