Adding elements to an array within a JSON object in Angular: What you need to know

Within my json object named "flowComponents," there is a string called "name" and an array of strings labeled "edition." As an example:

    {
  "_id": "553e87f3205465e83b46999b",
  "name": "FLOWCOMPONENT_CONTACTCOMBINATION_EDITION",
  "__v": 0,
  "edition": [
    "billing",
    "billingDelivery",
    "default",
    "deliveryAddressOnly",
    "deliveryBillingLicensee",
    "deliveryBillingLicenseeWithWrapper",
    "deliveryLicensee",
    "deliveryOnlyCopyToAll",
    "licenseeDelivery",
    "sassDefault",
    "sassDeliveryOnlyCopyToAll"
  ]
}

In order to incorporate/append another edition to this existing flowComponents object, I have designed a form featuring a dropdown with the names of the current flowComponents and a text area that generates an array from each line of text:

<form ng-submit="addToExistingFlowComponent()">
    <div class="interact">
        <select ng-model="existingName" chosen options="flowComponents" ng-options="item as item.name for item in flowComponents" data-placeholder="Select a flow component...">
            </select>
    </div>

    <div class="interact">
        <label class="interact-label">Enter each edition on a new line.</label>
        <textarea id="text_area" placeholder="Edition" ng-model="existingEditionList" ng-list="&#10;" ng-trim="false"></textarea>
    </div>
    <button type="submit">Submit</button>
</form>

This function in my controller is responsible for adding editions:

$scope.addToExistingFlowComponent = function(){
  if(!$scope.existingName || $scope.existingName === '') { return; }

  var existingFC = $scope.existingName._id;

  sendAppData.postEdition( existingFC, {
    edition: $scope.existingEditionList
  });

  $scope.existingName = '';
  $scope.existingEditionList = '';
}; 

Furthermore, here is the method used to post data to the server:

this.postEdition = function(existingFC, newEdition) {
   return $http.post('/new-flow-component', newEdition).success(function(data){
        flowComponents.push(data);
    });
};

An issue arises where the data is being pushed to a new object rather than being added to the existing one. Though I can pass the _id of the existing object into the existingFC parameter, I am struggling to access it within the function(data) in order to include it in the appropriate edition array.

Answer №1

Your code has been updated to allow the new editions from the text area to be added to your selected edition array without posting to the server. The submitted "new" editions are now appended directly to the edition array. Check out this Plunker example for reference: http://plnkr.co/edit/U2BE9Sdlictj9dEIWkjc?p=preview

I hope this solution works for you.

Modified Controller:

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

$scope.flowComponents = [{
  "_id": "553e87f3205465e83b46999b",
  "name": "FLOWCOMPONENT_CONTACTCOMBINATION_EDITION",
  "__v": 0,
  "edition": [
    "billing",
    "billingDelivery",
    "default",
    "deliveryAddressOnly",
    "deliveryBillingLicensee",
    "deliveryBillingLicenseeWithWrapper",
    "deliveryLicensee",
    "deliveryOnlyCopyToAll",
    "licenseeDelivery",
    "sassDefault",
    "sassDeliveryOnlyCopyToAll"
  ]
}]

$scope.addToExistingFlowComponent = function(){
  if(!$scope.existingName || $scope.existingName === '') { return; }

  var existingFC = $scope.existingName._id;
  var newEdition = {
    edition: $scope.existingEditionList
  };

  console.log($scope.existingName);
  console.log(newEdition);
  for(var i=0;i<$scope.existingEditionList.length;i++){
    $scope.existingName.edition.push($scope.existingEditionList[i]);
  }

  console.log($scope.flowComponents);

  $scope.existingName = '';
  $scope.existingEditionList = '';
}; 

}); 

Your Updated HTML Form:

<body ng-controller="MainCtrl">

    <form ng-submit="addToExistingFlowComponent()">
    <div class="interact">
        <select ng-model="existingName" chosen options="flowComponents" ng-options="item as item.name for item in flowComponents" data-placeholder="Select a flow component...">
            </select>
    </div>

    <div class="interact">
        <label class="interact-label">Enter each edition on a new line.</label>
        <textarea id="text_area" placeholder="Edition" ng-model="existingEditionList" ng-list="&#10;" ng-trim="false"></textarea>
    </div>
    <button type="submit">Submit</button>
</form>

  </body>

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

What is the best way to save user session variables in a MEAN.JS application?

I have chosen to utilize MEAN.JS for my project. I need to save a parameter for each user throughout their session on the website (from when they first open the site until they close their browser, even if they do not log in). This parameter should be ac ...

The function will provide the value prior to the execution of the Jquery image loading

if (DataService.Validation(file)) { //angularjs call to api controller }; //DataService Validation: function (file) { var Url = URL.createObjectURL(file); var img = new Image(); $(img).load(function () { var imgwidth = this. ...

Syntax error encountered with the null-coalescing operator (`??`)

Encountering Syntax Errors After Upgrading Angular Plugin I am facing some syntax errors after attempting to upgrade a plugin in a system that was originally developed by someone else. Although I am relatively new to Angular, I tried to simply replace the ...

Leverage jQuery/JS to divide a lone <ul> element into four distinct <ul> lists

I'm working with a dynamically generated single list (<ul>) that can have anywhere between 8 and 25 items (<li>'s). Here's an example of the HTML structure: <ul id="genList"> <li>one</li> <li>two</l ...

React Native: LogBox now including all warnings

Looking for a way to use LogBox to filter out specific log messages, but despite my attempts to ignore them, they still show up in the console... "react-native": "0.68.2", In my main file (index.js), this is how I've tried to impl ...

The website functions well in responsive design mode on an iPad screen, but encounters issues when viewed on an actual

The website is functioning well in responsive design mode on an iPad screen, however it seems to be having some issues specifically on iPad devices. I have tested it on all other devices and it works perfectly fine, but for some reason not on iPads. Feel ...

How to verify the presence of data within an array using PHP

In my Codeigniter 3 project, I am tasked with comparing two JSON objects. Here is the first JSON data that needs to be checked: [ { "id":23456, "name":"Some data" }, { "id":98765, ...

Learn the step-by-step guide on integrating Angular 2 into Codeigniter 3

Currently, I am using Codeigniter 3x and have been using and learning it for a month. Now, I want to start learning a JavaScript framework like Angular, but I'm not sure how to install or use Angular in Codeigniter. Can anyone guide me on this? Is it ...

Unraveling deeply nested array objects in JSON with Java Script/jQuery

I need help working with a JSON file that looks like the following: {[ {"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}, {"Folder":[ {"name":"John"}, {"name":"Anna"}, {"Folder":[ {"name":"gg"}, ...

Capture data from a Telegram bot and store it in a Google Sheet

I am trying to use a spreadsheet through a Telegram bot as a TODO list so that when I input something on my phone, it is saved in the spreadsheet. (I'm following this tutorial https://www.youtube.com/watch?v=XoTpdxbkGGk, which seems accurate with Goog ...

The process to reset a component's state when using router.push to navigate back to the same component

I am facing an issue with resetting the state on router.push in my project. I have a header component that includes a search option. When a user searches for something, router.push redirects them to '/search/${search}'. On the search page (SSR), ...

validation using ajax and php

One question I have is, when I include document.getElementById('myPassword').value); in the validarDados function, it corresponds to valor. Then I need another variable, but valor1 isn't working as expected. The result of echoing $valor1; is ...

Utilize Newtonsoft JSON for deserializing JSON objects

I have a JSON data that looks like this: {"NewMessage":[{"Id":-1,"Message":"Test","MessageName":"test1"}],"OldMessage":[]} and I am trying to convert this JSON into objects in my class. This is what my Class looks like: public class NewMessage{ public ...

When the virtual keyboard is opened on the Nexus Player using an Android Cordova app, the first character is automatically typed

While my question may be specific to a particular device, I am seeking insights on how to prevent a common issue from occurring in general. My ReactJS app has a build for Android using Cordova, with one of the supported devices being the Nexus Player. The ...

Best practices for efficiently utilizing setInterval with multiple HTTP requests in NodeJS

Imagine you have a collection with 3 to 5 URLs. You want to send requests every 5 seconds, one by one. Here is how I approached this: setInterval(() => { array.forEach(element => { request .get(element.url) .on('response', ...

AngularJS ng-repeat - cascading dropdown not refreshing

I'm dealing with an AngularJS issue where I'm trying to create a cascade dropdown like the one below: <div class="col-sm-2 pr10"> <select class="PropertyType" ng-controller="LOV" ng-init="InitLov(140)" ng-model=" ...

Determining the victorious player in a game of Blackjack

After the player clicks "stand" in my blackjack game, my program checks for a winner. I am using AJAX to determine if there is a winner. If there is a winner, an alert will display their name. Otherwise, the dealer will proceed with making their move. Any ...

Retrieving JSON data in Perl

Struggling with accessing json values (translated from xml). foreach my $PORT (0..$#PORTS) { print Dumper $PORTS[$PORT]->{'neighbor'}; if (defined($PORTS[$PORT]->{'neighbor'}->{'wwn'}->{'$t'})) ...

What is the method for creating a JavaScript array that closely resembles the provided example?

My task is to create an addRows method using specific data structure as shown below. data.addRows([ ['UK', 10700,100], ['USA', -15400,1] ]); However, the data I have available is in a different format. How can I transform ...

Do not reload the page after a successful ajax request

I'm using an Ajax section to submit data in Laravel. I want the page to not reload if the submission is successful, but to reload if there's an error. Currently, when there is an error, the page reloads correctly. However, I'm facing an issu ...