What is the process for obtaining a JSON file in AngularJS upon clicking a button?

Starting off with AngularJS and feeling excited.

I have successfully created a form with two input boxes.

Just below the input boxes, I have added:

<input ng-model="id.todoList" type="text" name="input" placeholder="Enter tasks here">
<input ng-model="id.todoList1" type="text" name="input" placeholder="Enter tasks here">

After entering the values in the inputs,

I managed to store them as an array. Done!

Whenever I click the submit button, the form inputs get pushed into the array.

However, there's one major issue...

If I enter details for 3 users and then try to add more, the previously stored 3 user details also get overwritten.

Any help on how I can fix this?

Here is the fiddler link for reference: Fiddler Link

Answer №1

To create an array of JSON objects, make sure to include the todoList and todoList1 data.

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

app.controller('MainCtrl', function($scope) {
  $scope.todos = []
  $scope.id = {   // Defining the id object
    todoList: "",
    todoList1: ""
  }

  $scope.addTodo = function() {
    // Constructing a JSON array with 
    // keys todoList and todoList1
    $scope.todos.push({
      todoList: $scope.id.todoList,
      todoList1: $scope.id.todoList1,
    })
  }

  $scope.clearAll = function() {
    $scope.todos = []
  }

});

View DEMO

Answer №2

Here is an example for you to try:

<body ng-app="plunker">
    <div class="container" ng-controller="MainCtrl">
      <div class="main">
        <p>Todo App</p>
        <input ng-model="id.todoList" type="text" name="input" placeholder="Enter tasks here">
        <input ng-model="id.todoList1" type="text" name="input" placeholder="Enter tasks here">
        <button ng-click="addTodo()">Add</button>
        <ul>
          <li ng-repeat="todo in todos track by $index">
            {{todo}}
          </li>
        </ul>
      </div>
    </div>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script>

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

app.controller('MainCtrl', function($scope) {
  $scope.todos = []
  $scope.todoList = "";

  $scope.addTodo = function(){
    var temp =  $scope.id;
    $scope.todos.push({"todoList":$scope.id.todoList,"todoList1":$scope.id.todoList1});
    console.log($scope.todos);
    $scope.id.todoList = '';
    $scope.id.todoList1 = '';
  }

  


});
</script>
  </body>

Answer №3

Try switching to the following code snippet:

<button ng-click="addToDo(item)">Submit</button>

Here is how you can retrieve values from a form using JavaScript:

item.task
item.description

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

The local variable within the Angular constructor is not initialized until the ngOnInit() function is invoked

I am encountering difficulties with making backend calls from Angular. In my component, I am fetching the "category" parameter from the URL as shown below: export class ProductsComponent{ productList = [] category = "" $params; $products ...

Storing data with Laravel 5.3 using Storage::put and XMLHttpRequest

Attempting to send a file using DRAG & DROP with XMLHttpRequest. $images = $_FILES['images']; When I use foreach: foreach($images["name"] as $file => $name) and move_uploaded_file($images["tmp_name"][$file], $images_dir . $name it works ...

Is there a point in bundling NPM packages if they are ultimately going to be bundled by the project

I'm in the process of creating a TypeScript package for publication on NPM. My plan is to utilize this package in upcoming web development endeavors, most likely utilizing Vite. As I look ahead to constructing a future website with this module, I am c ...

Trigger a function in JavaScript by clicking on an element and passing its class

I have written the following code: <?php $extCount = 0; foreach($this->externalReferal as $externalReferal) { $extCount++; ?> <div class='fieldtestPct' > <div class='fieldItemLabel'> < ...

After utilizing the function, the forward and back arrows are no longer visible

After setting up my slideshow, I encountered an issue where clicking the next or previous buttons caused them to shrink down and turn into small grey boxes. Has anyone experienced this before? This relates to PHP/HTML if ($_SERVER['REQUEST_METHOD&ap ...

Tips on using Ajax to post in HTML

Here is the code I have been working on: <script type="text/javascript"> var xmlDoc; var xmlhttp; function loadRates() { xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = readRates; xmlhttp.open("GE ...

Unlock the Power of Core 2 MVC with the Cutting-edge Integration of

Looking for a solution on how to effectively use JQuery Datatables with Core MVC? Check out this helpful resource: Using jQuery DataTables Grid With ASP.NET CORE MVC I recently downloaded the sample project and made some modifications to fit my needs. It ...

An issue has arisen: It seems that properties of null cannot be accessed, particularly the 'toISOString' property

After upgrading the dependencies in my package.json to their latest versions, I encountered an error while accessing a page that calls this data. Given that the dependencies were outdated by at least 2 years or more, I suspect the issue lies with the updat ...

After submitting the form, I must only deactivate the checkbox that has been selected

Here is the HTML code I am working with: I have multiple checkboxes designed as buttons to select a room, but it's quite annoying when they all get selected at once. $("form").submit(function() { $('.seat input:checkbox').prop("disable ...

What is the best way to leverage an existing user database and integrate user authentication into a fresh project?

I have recently taken on the task of revamping an established project by creating a brand new frontend from scratch. After careful consideration, I have opted to develop a straightforward Vue/Node.JS project. Within the current framework lies a Postgres d ...

Showing the value of a JavaScript variable within an HTML input field

Here is an interesting HTML structure that includes a list and input field: <li> <span>19</span> </li> <li> <span>20</span> </li> ...

What is the best way to update an existing cookie value using angularjs?

Currently, I am working with AngularJS. When a button is clicked, I am setting a cookie and it works perfectly fine. However, when the page is refreshed and another button click occurs, a new value is stored in the array while the old cookie value becomes ...

Struggling to retrieve JSON data from the MercadoLibre API while consistently encountering the CORS error?

I have been attempting to access a mercadolibre API that provides JSON data I need to utilize. However, whenever I make an AJAX GET request, I keep receiving the same error: "Response to preflight request doesn't pass access control check: It does n ...

What is the best method for linking an HTML file to CSS, javascript, and image files?

I need assistance with running an HTML file along with its source files that I downloaded from the server. The HTML file is located in NSCachesDirectory and here is the code snippet I am using. Can someone please help me figure this out? NSArray *paths ...

Currently seeking user coordinates for Vue implementation

I recently started using Vue and I'm working on capturing the lat/long of a user to be used in other functions within Vue. Currently, I am retrieving the coordinates and plan to utilize them in an API but for now, I am just logging them. Although I c ...

Utilize jQuery to run a script once everything is prepared and loaded

My website utilizes ajax technology, and within the ajax page, there is a piece of javascript code that needs to run only after the entire ajax page has loaded. I have attempted to use the following: $( '#ajaxdiv' ).load(function() { } However ...

How should the nonce be properly set in the csp policy?

I've been attempting to incorporate a nonce into the csp policy but it's not functioning as anticipated. Here's the code snippet I'm currently using for testing purposes: server.js express.use(function(req, res, next) { res.set( ...

Performing an action once all AJAX requests have finished

I'm dealing with a situation where I have a click event triggering 3 ajax calls: $("#button").click(function(e) { e.preventDefault(); $.ajax(call1); $.ajax(call2); $.ajax(call3); some_function() //needs to be executed only afte ...

Why does the getOwnPropertyDescriptor() method in JavaScript include custom properties that are inherited?

As I delve into the world of JavaScript and Node.js, a question has arisen regarding the Object.getOwnPropertyDescriptor() function. Let's explore the following snippet of code: var rectangle = { width: 10, height: 5, get area() { ...

Looking to verify the validity of my email and phone number

Looking for some assistance in validating my email and telephone inputs for the contact form. The current code for email validation is incorrect, so I need help fixing it. It should be something like this: if(email.length == 0 || email.indexOf('@&apo ...