A guide on processing text line by line within a textarea and transforming it into JSON using AngularJS

Here is a textarea containing values in a specific format:

param01 : value01
param02 : value02

This is the code I have tried:

<div class="col-xs-4 input-container">
  <textarea id="gateway-params" ng-disabled="!edit">{{gatewayParams}}</textarea>
</div>

JavaScript function:

$scope.save = function() {
   for (var i = 0; $scope.gatewayParams; i++) {
      console.log(params[i]);
   }
 }

My goal is to read each line from the textarea and create a Javascript object based on it.

Best regards!

Answer №1

// Please refrain from adding empty key/value pairs.

Check out this plunkr example: http://plnkr.co/edit/Zea3zZqaagDdO4s8pZRC?p=preview

On the controller side:

$scope.text = 'param01 : value01\nparam02 : value02\nparam03 : value03\nparam04 : value04\nparam05 : value05\nparam06 : value06\n';    

$scope.actionme = function(){   
    var lines = $scope.text.split("\n");// separating lines
    var datas ={}; 
    for(var i in lines){
      var line = lines[i].split(":"); // extracting key / value pairs
      // include only if key and value are not empty
      if((line.length ==2)&&(line[0].trim()!="")&&(line[1].trim()!="")){
        datas[line[0].trim()]  = line[1].trim();
      }
    }
    console.log(JSON.stringify(datas));
}

HTML View:

<div ng-controller="Ctrl">
   <textarea ng-model="text"> 
   </textarea>

  <button ng-click="actionme()">click</button>

</div>

Answer №2

By utilizing ng-model within your textarea, you have the ability to capture the content as a string and then parse it within your controller or directive.

To accomplish this, you can use

.split('\n');

This will allow you to split your string into an array of strings by new lines. As for the parsing process, I'll leave that part up to you. However, here is how you can structure your object:

var property = "example01";
var value = "output01";
var obj = {};
obj[property] = value;

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

Enlarging the current division while reducing the size of the others when hovering

Currently, I am working on a school project that involves creating a slideshow on a webpage. However, I have reached a point where I am unsure of how to proceed. Here is the progress I have made so far: body { background-color: #252525; } #wrapper { ...

Avoiding the addition of identical objects in the array

I have expertise in JSON, and I need to be able to select multiple skills from a dropdown using model.skills. I have a function called multipleSkills() that pushes the selected values into an array called arrayvalues[], but I want to ensure that duplicate ...

Steps for running example of JavaScript colormap:

After discovering a JavaScript example on this GitHub repository, I decided to give it a try by following the steps outlined in this helpful answer, while using Windows 7. Here's what I did: First, I installed node. Next, I installed browserify. The ...

Tips for incorporating a new item into ng-repeat at a specific position in the array?

<!-- if (index == 2) <div>{{data.customText}}</div> --> <div ng-repeat-start="product in products">{{product.headline}}</div> <div ng-repeat-end>{{product.text}}</div> Suppose I am presenting a lineup of 5 product ...

The v-select menu in Vuetify conceals the text-field input

How can I prevent the menu from covering the input box in Vuetify version 2.3.18? I came across a potential solution here, but it didn't work for me: https://codepen.io/jrast/pen/NwMaZE?editors=1010 I also found an issue on the Vuetify github page t ...

Suggestions for rendering this JSON format

I am attempting to iterate through this JSON format, I have tried following this method but I am a bit confused with my code How to iterate JSON array in JavaScript?. Also, I have a question, is this actually a valid JSON format or something different bec ...

How to utilize jQuery to eliminate HTML onchange code

This block of code features an HTML onchange attribute as well as the use of jQuery's change event on an input text. I want only the jQuery change event to take precedence. I have attempted to use both unbind and off without success. Can someone prov ...

convert a screenplay to javascript

I have a script that can be used to calculate the distance between 2 coordinates. The code is a combination of PHP and JavaScript. I am interested in moving it into a standalone JavaScript file but not sure how to proceed. Below is the script related to & ...

Unable to display any posts in my React application, no content is being produced

I am currently in the process of developing a blogging site using React by following a tutorial. However, I have encountered an issue where the posts are not appearing on the screen. Here is the link to my GitHub repository: https://github.com/AkshatGarg2 ...

Encountering an issue with core.js:15723 showing ERROR TypeError: Unable to access property 'toLowerCase' of an undefined value while using Angular 7

Below, I have provided my code which utilizes the lazyLoading Module. Please review my code and identify any errors. Currently facing TypeError: Cannot read property 'toLowerCase' of undefined in Angular 7. Model Class: export class C_data { ...

Refresh the webpage content by making multiple Ajax requests that rely on the responses from the previous requests

I am facing a challenge where I need to dynamically update the content of a webpage with data fetched from external PHP scripts in a specific sequence. The webpage contains multiple divs where I intend to display data retrieved through a PHP script called ...

Pressing a button to alter the text color

While experimenting, I attempted to alter the text color of my HTML using JavaScript. After a few attempts, I came to the realization that I cannot change the color if I am already changing it in CSS. Does this mean CSS is executed at the end? Also, how ca ...

Angular 2 ensures that all of the columns receive updates

Currently, I am facing an issue with my angular 2 editable table created using ngFor. The problem arises when I attempt to edit one column, as all the columns get updated with the same value. One solution could be creating a new component, but I would pr ...

Images in HTML that continuously refresh themselves

I have a challenge where I need to create a dynamic dashboard displaying changing data images every few seconds. The idea is to update the image source by appending a query parameter, for instance, from /images/graph1.png to /images/graph1.png?a=1 after 10 ...

Hiding links in javascript

I currently have a hyperlink <a href="url1">url1</a>. Interestingly, I have noticed that some websites utilize JavaScript to display this as url1 but in reality, it redirects to url2. When you hover over the link, the original url is not visib ...

What is the process for integrating a factory into a controller?

Hello, I'm currently new to working with angularjs and I'm facing some challenges while trying to inject a factory into my controller. The factory seems to be functioning properly as I can set data in it without any issues. Below is the code snip ...

What are the steps to caching a message using discord.js?

In order to create a Discord bot with a command !edit [id] [new content], I have implemented the following code: if (MessageContent.startsWith('!edit ')) { if (authority >= 3) { //if false if (args.length < 3) { ...

Mixing various templates into a single outlet in ember.js

I have been working on an ember application that allows users to create, edit, and delete users, as well as view a list of all users. The app was created by following a tutorial on Ember (as I am still learning), but I am facing an issue. Currently, all th ...

What is the best way to create a gradual color change in each individual cell instead of changing all at once?

Looking for some help with a grid I'm working on. I've got the cells changing colors like I want them to, but they're all changing at once. What I really need is for them to light up in a specific order - Yellow, Green, Blue, White, Orange. ...

Displaying extensive JSON data sets leads to browser freezing, crashing, or becoming unresponsive

I have encountered an issue while working with a large json data-set consisting of 1500+ records related to hotels. When trying to render this information into HTML, the browser ends up hanging, crashing, or becoming unresponsive. The project in question ...