Encountering naming problem with ng-model, attempting to create an array but receiving a hash instead

Trying to create an array using ng-model,

<div ng-repeat="n in [1, 2, 3]">
  <input type="text" class="form-control" ng-model="headers[$index].key">
  <input type="text" class="form-control" ng-model="headers[$index].value">
</div>

After using angular.toJson ($scope.headers), I received:

{
  "headers": {
    "0": {
      "key": "xxx",
      "value": "yyy"
    }
  }
}

However, my desired output was:

{
  "headers": [
    {
      "key": "xxx",
      "value": "yyy"
    }
  ]
}

Is it possible to achieve this format?

Answer №1

Does this align with your expectations?

VIEW DEMO

index.js

<!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="d8b9b6bfadb4b9aaf6b2ab98e9f6ecf6a0">[email protected]</a>" src="https://code.angularjs.org/1.4.2/angular.js" data-semver="1.4.2"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <div ng-repeat="object in transformedData">
      <input type="text" class="form-control" ng-model="object.key">
      <input type="text" class="form-control" ng-model="object.value">
    </div>

    <pre>{{transformedData}}</pre>
  </body>

</html>

app.js

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

app.controller('MainCtrl', function($scope) {

  var data = {
    "headers": {
      "0": {
        "key": "xxx",
        "value": "yyy"
      }
    }
  };

  $scope.transformedData = transformData(data.headers)

  function transformData(data){
    var arr = [];
    for(var key in data){
      arr.push(data[key])
    }
    return arr;
  }

});

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

Tips for implementing conditional sections in an Angular template HTML file

Creating three different tables as described below: There is a significant amount of repetitive code. The only variation in each table is the studentPermissions[] array, which contains three objects for each student. Therefore, I am simply changing it ...

Update the image with a new one using jQuery and PHP, then refresh the page to see

I'm currently utilizing simpleImage, a PHP image manipulation library. My aim is to externally rotate an image using AJAX and replaceWith functions. It successfully replaces the image, but unfortunately it doesn't refresh after rotation. Here&ap ...

Problem encountered while using AJAX to load a PHP script, triggered by an onclick event;

My expertise lies in HTML, CSS, JavaScript, and PHP. However, I find myself lacking in knowledge when it comes to jQuery and Ajax. While I work on web design projects involving bars and nightclubs that prioritize style over performance, my current job dema ...

What causes errors in my AJAX request based on the particular file extension?

Utilizing JavaScript and jQuery, I have a function that loads data using $.get(url, function(response){ /* ... */});. The data is retrieved from a text file and handled within the response function of the JavaScript. Recently, I encountered an issue on my ...

Initial space in model variable not being displayed

Hey there, I am working with a model variable called "name" that is linked to a span element like this: <input type="text" ng-model="name"> <span ng-bind="name"></span> My goal is to display the text entered in the input field without r ...

What is the best way to incorporate a class creation pattern in Typescript that allows one class to dynamically extend any other class based on certain conditions?

As I develop a package, the main base class acts as a proxy for other classes with members. This base class simply accepts a parameter in its constructor and serves as a funnel for passing on one class at a time when accessed by the user. The user can spe ...

The conditional expression in AngularJS is failing to execute

Having trouble with my login page that uses AngularJS to evaluate the username and password. Even when I input correct values, the conditional statement in the controller seems to return false. Below is a snippet of my HTML file: <div class="row"> ...

What steps can I take to make sure the JavaScript runs and updates the images correctly?

Trying to adjust image sizes with JavaScript. Followed a jsfiddle example, but it's not working on the page. Seems like the script is misplaced. How can I fix this? <!DOCTYPE html> <html> <head> <meta http-equiv="cont ...

Update a specific HTML element when the result of an equation is modified

I need assistance with my angularjs website development project. I have implemented content-specific tabs, each with its own unique content. When a tab is selected, only the corresponding content should be displayed. The tabs are assigned IDs in the contro ...

Remove any list items that do not possess a particular class

My ul list contains several lis, and I need to remove all li elements that do not have children with the class noremove. This is the original HTML: <ul> <li>Item 1</li> <li>Item 2 <ul> <li>I ...

Updating the values of parent components in Vue.js 3 has been discovered to not function properly with composite API

Here is a Vue component I have created using PrimeVue: <template lang="pug"> Dialog(:visible="dShow" :modal="true" :draggable="false" header="My Dialog" :style="{ width: '50vw' }" ...

Breaking on newline, excluding newline-space in JavaScript

I want to divide my string into an array based on new lines, excluding those that start with a space. ORGANIZER;<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3758455056595e4d524577524f565a475b521954585a">[email prot ...

javascript download multiple PDF files on Internet Explorer

I am facing an issue with downloading multiple PDF files In my list, I have various a elements with links to different PDF files. I created a loop to go through each a element and generate an iframe using the value of the href as the source. This solutio ...

Problem with declaring Javascript objects

Exploring the world of OOP for the first time, encountering a small challenge: const panel = { image : imgs[24], proportion : this.image.height / this.image.width, height : this.image.height - (scale), width : height / proportion, ...

How do I retrieve the HSL value for a color selected using an input of type 'color' in JavaScript?

I am faced with a creativity block and don't know where to begin. My goal is to develop functions that can manipulate the HSL values once I have access to them. Specifically, I am interested in modifying the light value, which is why I require it in ...

stopPropagation() halts the propagation in the opposite direction

I encountered an issue while attempting to create a non-clickable div. While it does stop propagation, it doesn't prevent what should be stopped and allows things that shouldn't be clickable. js //screen has set stopPropagation $("#smokeScree ...

Automatically adjusting input box size and position in real-time

I am working on a form that includes a button and an input field. When the user clicks on the button "ADD MORE FIELDS," I want to dynamically generate a new input box. Although I have tried using code from this jsfiddle link and it works, my goal is to ach ...

Enhance data validation in PHP

I love using Nicedit as a text editor because it allows me to easily add bold and italic formatting to my form fields. However, when I try to store this text in my database, Nicedit adds HTML tags for bold, italic, and other formatting styles. Is there a ...

Tips for creating a Material UI (next) dialog with generous top and bottom margins that extend off the screen

I am encountering a challenge with the layout. What am I looking for? I need a modal dialog that expands vertically, extending beyond the screen, centered both horizontally and vertically, with minimal margin on the top and bottom. Is this feature not d ...

Trouble arises when attempting to categorize an array of objects in JavaScript

My array consists of various objects: [{id: 1, name: 'Apple', category: 'Fruit'} {id: 2, name: 'Melon', category: 'Fruit'} {id: 3, name: 'iPhone', category: 'Phone'} {id: 4, name: 'Samsung Ga ...