Change a JSON Array into an HTML string that is wrapped using an Angular service

Currently, I am attempting to integrate a wysiwyg editor into my Angular application. The objective is to retrieve an array of objects by querying an endpoint, then format the data within each object based on its property name with different HTML tags. Finally, all the formatted data will be combined into a string and displayed in the wysiwyg editor within my app.

For example, given JSON like this:

[   
    {
    "name": "steve",
    "age": 33,
    "profile": "http://www.profile.com/steve",
    "location": "New York"
    },{
    "name": "john",
    "age": 25,
    "profile": "http://www.profile.com/john",
    "location": "LA"
    },
]

The output would be:

"<b>Steve - New York</b>
<br>
<a href='http://www.profile.com/steve'>Url</a>
<br>
<span>33</span>
<br>
<br>

<b>John - LA</b>
<br>
<a href='http://www.profile.com/john'>Url</a>
<br>
<span>25</span>
<br>
<br>"

Although this functionality is not specific to Angular, it would be beneficial to encapsulate this logic within a service for reusability throughout the application.

I am uncertain about how to structure this code. Any suggestions or ideas?

EDIT: To clarify, the reason behind implementing this feature is to accommodate non-technical users who need to edit content in the wysiwyg editor and export it as a PDF file from the application. Both the wysiwyg editor and backend system require the content to be in a single HTML-tagged string format.

Answer №1

Why bother reinventing the wheel when you can simply utilize a reliable WYSIWYG editor like TinyMCE? You can integrate it with Angular using the Angular-UI extension available here:

https://github.com/angular-ui/ui-tinymce

All you need to do in your HTML is:

<textarea ui-tinymce="tinyMceOptions" ng-model="parsedResponse"></textarea>
<button ng-click="convertToPdf()">DOWNLOAD PDF NOW</button>

In your controller or directive:

$scope.tinyMceOptions = {/*Customize as needed*/};

$scope.parseMyResponse = function(data) {
  // manipulate data and return as HTML string
  return data;
};

$http.get('/your/resource/url').success(function(result) {
  $scope.parsedResponse = $scope.parseMyResponse(result);
});

$scope.convertToPdf = function() {
  // convert $scope.parsedResponse to PDF
};

Note: If you prefer placing these functions in a service, you can create one as follows:

angular.module('app')
  .service('Util', function() {
    return {

      wrapInTag: function(tagName, value) {
        return '<' + tagName + '>' + value + '<' + tagName + '/>';
      },

      parseMyResource: function(response) {
        htmlString = '';
        angular.each(response, function(item) {
          htmlString += this.wrapInTag('h1', item.title);
          htmlString += this.wrapInTag('b', item.id);
          // Additional manipulation...
        });
        return htmlString;
      }

    };
  });

Then in your controller:

angular.module('app')
  .controller('MyCtrl', function(Util){
    // Util functions can be used here...
  });

I've provided sample code for converting JSON to HTML strings, but the specifics of your parsing function will depend on your requirements and data model structure. There's no one-size-fits-all method for transforming JSON into HTML.

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 process for converting several files into a base64 string?

I have a component set up like this: <input type="file" multiple @change="toBase64Handler($event)"> <script> data() { return { files: [], } }, methods: { tobase64Handler(event) { // implementation } } </script> I w ...

I'm curious why I need to add an extra await in my Vue.js unit test whenever multiple calls are made to my Firebase auth mock

In my vue.js application with firebase authentication, I encountered an issue while testing the Login.vue component. To mock firebase auth, I had to simulate the configuration file used for initializing firebase (named firebase.config). It's worth men ...

"Experience the new Bootstrap 5 feature: Off-Canvas sliding from left to

I encountered the code snippet below on the official bootstrap 5 demo. Despite my efforts, I am struggling to figure out how to relocate the off-canvas menu from Left-to-Right. The divergence between the documentation code referencing offcanvas-start and t ...

Converting a JSON object to a class in ASP.NET MVC - A step-by-step guide

Having trouble converting the JSON object below to a class in Asp.Net MVC. { "Name.Test":"fsafasfda" } If you have any suggestions, they are greatly appreciated. The situation is as follows in an ASP.NET action: [HttpPut] public JsonResult Te ...

Retrieving data from the server using Unity's deserialization function

After spending several hours attempting to deserialize data from my server for our high score system, I encountered an error: ArgumentException: JSON must represent an object type. Here is the code snippet showing how I am deserializing (scores is of t ...

Manage and maintain database structure with synchronization capabilities

I am tasked with creating a web application that can function offline using Local Storage or IndexedDB. Currently, my server has schema v2 which includes additions such as new tables or fields, while my local app is using schema v1. I am looking for a so ...

Utilizing Node and Electron to dynamically adjust CSS style properties

Having a dilemma here: I need to access the CSS properties from styles.css within Electron. Trying to use document.getElementsByClassName() won't work because Node doesn't have document. The goal is to change the color of a specific div when the ...

Issue with AngularJS filter not functioning properly

I have a specific situation where I am using an ng-repeat directive in the following manner: {"ng-repeat" => "city in cities() | filter: search"} In this context, each city object is structured like so: { attributes: {name: 'Boston'} } Furt ...

What is preventing me from concealing my input field when its type is set to "file"?

I've been attempting to conceal my input field of a file type, but even with the hidden attribute, it refuses to hide. https://i.sstatic.net/jyMrn.png https://i.sstatic.net/P59wV.png Interestingly, once I remove type="file", the code succe ...

AngularJS - Trouble loading directive

I'm facing some challenges with a custom directive I've created and it's not functioning as expected. Below is the code for my directive: angular .module('thermofluor') .directive('myCustomer', function() { return ...

Retrieving values with a variable serving as the key

My goal is to utilize the object key as a variable in my code. I've successfully extracted the object key (c000_01), but now I need to access the corresponding value of that object, which is "Master". Below is a snippet of the data structure: const ...

How can nested json be sorted effectively based on two specific fields?

Example Data: [{ 'ID': objID(abc123), 'Department': 'IT', 'Employees': [ { 'ID': 3, 'StartDate': '24-12-2022T08:30', 'active': true }, { ...

Replace the term "controlled" with "unleashed" when utilizing the file type input

In my app, I have defined multiple states like this: const [state,setstate]=React.useState({headerpic:'',Headerfontfamily:'',Subheaderfontfamilty:''}) And to get an image from my device, I am using the following input: &l ...

Updating a JSON file with new object using node.js

Currently, I am attempting to insert a single object into an extensive JSON file. My approach involves parsing the entire file using FS and JSON.Parse, adding the new JSON object in memory, and then rewriting the file. While I am aware of FS's append ...

What is the best way to compress all folders, including the main directory?

I am working on a PHP script where I need to zip all directories, including the root directory. For instance, if my script file is located at /practice/zip/index.php, and I want to create a zip archive for the entire /practice directory. Currently, my sc ...

The behavior of the 'typeof null' function in JavaScript is not functioning

I have a collection of objects where each object contains a key and an array as a value. You can see what I mean in this image. Some of the arrays had less than 20 elements, so I wrote some code to pad them with zeros. The result of running my code can be ...

Memory Match: Picture Edition

In this memory game, letters are used. I had considered changing it to a picture-based game, but I faced difficulty in generating images and incorporating them into the array. <script> var memory_array = ['A', 'A', 'B&ap ...

Guide on accessing CGI Script response using AJAX

Greetings, Here is the situation: I'm working on a login form. Once the submit button is clicked, it needs to trigger a CGI script called "someurl?userName=user&password=pwd". Depending on the response from the script, I should be able to navigat ...

Leveraging dependency injection in Angular 2+ with pre-loaded models

I desire the ability to create an instance of a model using a constructor while also providing injected services to that model. To clarify, I envision something like this: var book = new Book({ id: 5 }); // creates instance, sets id = 5 book.makeHttpCa ...

Passing data retrieved from fetch requests in ReactJS using context: Best practices

Just started learning React and need some help. I'm trying to pass variables with json data to a component for further use but running into errors. What changes should I make to use variables with json data from Store.js in the product.js component? T ...