AngularJS: ng-model with dual objects

I am currently working on achieving a double nested object structure, however, my code is generating an array inside an object instead.

<div ng-if="newResultUnits()" ng-repeat="set in sets" ng-model="newexercise.sets[$index]">
                    <label>Set {{$index+1}}</label>
                    <label>
                        <label>
                            <input type="text" ng-repeat="resultUnit in newResultUnits()" ng-model="newexercise.sets[$parent.$index][$index].value" placeholder="{{resultUnit.name}}">
                        </label>
                    </label>
                </div>

Here is an example of the current output (the name attribute is added later):

{  
       name:"MultiTest",
       sets:[  
          { 
             0:{ 
                value:"10",
                name:"Kg"
             },
             1:{ 
                value:"10",
                name:"Wdh"
             }
          }
       ]
    }

This is how I want it to be structured (Please notice the double [[ and the missing 0:):

    {
      "name": "MultiTest",
      "sets": [
        [
          {
            "value": "10",
            "name": "Kg"
          },
          {
            "value": "10",
            "name": "Wdh"
          }
        ]
      ]
    }

If there was any confusion between Array and Object in my explanation, I apologize! Thank you for your help.

Answer №1

Start by properly initializing your data structures. In the controller, begin with:

$scope.newexercise = { sets: [] };

This lets Angular know that $scope.newexercise should be an array. Then in the template, use ngInit on each inner loop like this

ng-init="newexercise.sets[$parent.$index] = []"
:

<div ng-repeat="set in sets">
    <label>Set {{$index+1}}</label>
    <label>
        <label>
            <input type="text" 
                   ng-repeat="resultUnit in newResultUnits()" 
                   ng-init="newexercise.sets[$parent.$index] = []" 
                   ng-model="newexercise.sets[$parent.$index][$index].value" 
                   placeholder="{{resultUnit.name}}">
        </label>
    </label>
</div>

Check out the demonstration here: http://plnkr.co/edit/s1rInT8rLg50ISsSVxyV?p=preview

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

Encountering NodeJs Error 401(Unauthorized) while implementing passport-jwt in my project

I am currently developing an authentication application using Node.js, MongoDB, and the Passport-JWT middleware. I have successfully implemented the login functionality and I am able to obtain a token. However, when trying to access the user profile after ...

Unable to understand the reason behind the malfunctioning of angular binding in the codepen script

I am attempting to utilize angular in my codepen project, as it seems to be supported. However, I am encountering an issue where I am unable to bind to my controller's $scope object for some reason. I have experimented with different versions of angul ...

What makes realtime web programming so fascinating?

Working as a web developer, I have successfully created various real-time collaborative services such as a chat platform by utilizing third-party tools like Redis and Pusher. These services offer straightforward APIs that enable me to establish bidirection ...

Utilizing Web Worker threads to enhance performance in Google Maps

Currently, I am experimenting with web worker threads to retrieve directions between various pairs of locations simultaneously and save the data in a file at the end. The process worked smoothly when attempted sequentially. I am using npm live-server to sh ...

What is the best way to retrieve ID tags and other element values for a string element stored in an array?

Is there a way to use document.querySelector("#") on an input element (and check if it is checked) that is saved in a string and then retrieved by innerHTML? I'm having trouble figuring out how to access it. I am trying to loop through an array and l ...

What is the process for implementing a CSS theme switch in a CHM file and ensuring that it remains persistent?

Welcome to my tech world Greetings! I am a tech writer with a side interest in scripting JavaScript/jQuery for our help file (CHM file). While I consider myself a beginner in JS scripting, I have ventured into the realm of dynamic theme swapping within CH ...

Is there a way to restrict the amount of user input that is allowed?

Is it possible to restrict the input quantity when using the built-in arrow icon in the text field, but not when typing manually? https://i.sstatic.net/jjogP.png <TextField variant="outlined" label="Quantity" onChan ...

Disable multiple buttons at once by clicking on them

What is the best way to disable all buttons in a menu when one of them is clicked? Here is my code: <div class="header-menu"> <button type="button"> <i class="fa fa-search" matTooltip="Filter"& ...

An automatic selection in my AngularJS drop-down menu

I am currently utilizing AngularJS to develop a basic web application. My goal is to have the values of city A displayed as the default choice in my select dropdown. index.html <body ng-controller="MainCtrl"> <select ng-model="selectedCity" ...

Failure in Testing: ReferenceError indicating that SpeechSynthesisUtterance has not been defined

In a recent project, I decided to add text-to-speech functionality and opted for a plain JavaScript solution. (https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance) Currently, I am using [email protected] and [email protecte ...

A step-by-step guide to showing images in React using a JSON URL array

I successfully transformed a JSON endpoint into a JavaScript array and have iterated through it to extract the required key values. While most of them are text values, one of them is an image that only displays the URL link. I attempted to iterate through ...

The `res.download(filepath)` function seems to be failing to initiate a download request on the user's

I'm currently working on a project involving image compression using node and react. The issue I'm facing is that when the server sends the image to the client using res.download(filepath), the download doesn't trigger on the client side. Ho ...

The Discord OAuth2 bot fails to assign roles to authenticated users

While working on OAuth2 login for my website, I encountered an issue. After a user successfully logs in through OAuth2, the bot should assign a role to them on my Discord server. However, when I tested the login process myself, the bot returned an error me ...

Adding x days to a Unix timestamp can be achieved by converting the Unix timestamp

Currently, I have the following code snippet: let currentTS = Math.floor(+new Date() / 1000) This code successfully retrieves the current date in a unix timestamp. However, my goal now is to append an additional 14 days to this unix timestamp. Could some ...

JavaScript - Assigning the same value to 2 properties but console log displays them as distinct values

While iterating through an array of documents, I am encountering a strange issue where setting two properties to the same value results in them having different values when logged using console.log. Here is the code snippet: this.logicItem.$promise.then( ...

Issues with Sound Not Playing When Button is Clicked in Python Flask

My goal is to trigger an audio sound when the Delete button is clicked. I've created an external JavaScript file and successfully linked it with Flask. index.html <a href="/delete/{{todoitem.item_id}}" class="btn btn-danger" onclick="playDelSound ...

I am curious about the significance of the "=>" symbol within the Ionic framework

I utilized the documentation provided on the Ionic website to incorporate Firebase into my mobile application. this.firebase.getToken() .then(token => console.log(`The token is ${token}`)) // store the token server-side and utilize it for sending not ...

The drag-and-drop application failed to upload a video using Ajax

I am currently working on an application that allows users to upload files to a server with a drag and drop function. The app is functioning well for images, but occasionally encounters issues when trying to upload videos. I'm not certain if there&apo ...

Utilizing ngClick and ngDisabled with a templated anchor element

I am currently developing a directive as follows: module.directive('myButton', function () { var directive = { compile: compile, restrict: 'E', scope: { type: '@', click: & ...

Adjust picture based on the MaterialUI slider's value

I want to incorporate a discrete Slider component from Material UI into my React web app. The goal is to have the user change a picture every time they adjust the slider value, with the new image displayed in a specific div. I am wondering how I can achiev ...