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

Angular does not always interpret the value returned from a Promise.all call

One of the challenges I'm facing is related to the structure of my controller: controller.things = ['a', 'b', 'c']; controller.loading = true; controller.responses = []; controller.handlePromises = function(){ var pr ...

Even though I have assigned the value of $scope.product to $scope.editOrDeleteProduct, the former is still undergoing changes

Initially, I utilize my $scope.product within a table <tr ng-repeat="product in products ng-click="productClicked(product)"> <td>{{product.prod_name}}</td> <td>{{product.company}}</td> </tr> Subsequen ...

Creating a heading transition that moves from the bottom to the top with CSS

I am looking to add an animation effect to the H1 element in my program. I want it to smoothly appear from the bottom hidden position using a CSS transition when the page loads. How can I achieve this? Additionally, I need the height of the bounding elemen ...

What is the best method for ensuring that cheese rises to the top?

Is there a way to increase the value of the variable cheese? I suspect it has something to do with how the variable cheese is defined each time the JavaScript is activated, but I'm not sure how to go about it. Can you offer some guidance on this? & ...

Step-by-step guide on incorporating a new JSON object into an array to display its elements as components on a webpage

Could I adjust the state of an array by incorporating values from a data.js file as a starting point? The process involves executing the setAllThingsArray function to add a new element, determined by the setThingsArray function based on the previous state ...

Insert a zero in front of any single digit hour

What is the best way to add a leading zero before single digit numbers in time format? For example, how can we convert "0:3:25" (hh:mm:ss) to "00:03:25"? ...

What could be the reason for Sequelize to completely replace the record when updating in a put request?

I've been attempting to implement an "edit" feature within my project, but I've hit a roadblock in the process. Here's a snippet of the put request code: export const updateEvent = (event, id) => (dispatch, getState) => { request ...

Using Knex in ExpressJS to insert a list of entries into SQLite with unique field constraints

I'm currently facing an issue with inserting a list of exercises into an sqlite database. The app is built on express JS and I am utilizing sqlite3 and knex to handle interactions with the DB. My goal is to add a set of exercises into the table exerci ...

Importing classes in ECMAScript 6 does not work properly, causing issues when running scripts

I am currently learning Selenium Webdriver. I am facing an issue where I can't run a script with imported classes, but I am able to run it without classes using import functions only. To execute it, I use babel-cli in the following manner: node ./babe ...

Optical Character Recognition (OCR) tool

Does anyone have recommendations for a JavaScript OCR API that can easily be accessed via JavaScript? I'm searching for an API similar to this: upload an image along with the desired result type (e.g. numbers, objects, text, mixed, etc) and receive t ...

I'm a complete programming newbie and I want to start learning JavaScript, jQuery, and other programming languages. Where should I

Coming from a design background with zero programming knowledge, I have recently learned XHTML and CSS. Now, I am eager to expand my skills by mastering JavaScript, jQuery, and more. Where should I begin? This will be my first foray into programming. Whil ...

Displaying angularJS ui-grid columns in a lazy manner

Is there a way to efficiently load columns as needed? I have a large dataset with 5k columns and 100k rows. My framework is angularjs 1.5.7 along with angular-ui-grid ^3.x. The grid performs well with 100k rows and 100 columns, but when trying to load ove ...

Tips for arranging buttons horizontally in Angular

After adding a third button, I noticed that the buttons were now displaying in a column instead of a row. html: <div class="creator-button-container" *ngIf="isCurrentUserTheChannelCreator"> <div *ngIf="isChannelE ...

Exploring and identifying matching pairs within a JavaScript object

Currently, I have a JavaScript object that looks like this: records: [ { id: 1, name: michael, guid: 12345 }, { id: 2, name: jason, guid: 12345 }, { id: 3, name: fox, guid: 54321 }, { id: 4, ...

`A straightforward technique for establishing client-server communication using NodeJS`

Stumbling upon a valuable code snippet on GitHub for enabling straightforward server-client communication in NodeJS has been quite enlightening. Upon making some adjustments, the finalized structure of my code looks like this: The client (Jade + Javascri ...

The error message being displayed states that 'null' cannot be used as an object when evaluating 'response.productType'

Hey everyone, I'm fairly new to working with Ajax and I've encountered an error in my code that says: TypeError: 'null' is not an object (evaluating 'response.productType'). I'm not sure why this is happening. Below is th ...

What is the best way to interpret a nested JSON object?

Recently I've crafted an object that looks like this. myObj = { "name":"John", "age":30, "cars": [ "car1":"Ford", "car2":"BMW", "car3":"Fiat" ] } While it's pretty straightforward to read the name and age properties, I find ...

How can I iterate through multiple rows in JavaScript?

Feeling stuck, the simple yet dreaded for loop has become my nemesis and I could really use some guidance. Currently, I have a Google sheet with 3 rows (excluding headers) and 8 columns. As users input data via a web app, the number of rows will dynamicall ...

Nested Loop in React JS with Arrays

Hey there, I could really use some help with looping through a JSON array. It's similar to the layout of an Instagram or Facebook post. I have a nested JSON array and the code I tried isn't working as expected. I'm aiming for a view that res ...

Invoke a server-side function via JSON data

Need help with calling a server-side method from JSON. Below is the code I currently have: SERVER SIDE: [WebMethod] private void GetCustomer( string NoOfRecords) { string connString = "Data Source=Something;Initial Catalog=AdventureWorks;Trusted_Con ...