Tips for showcasing JSON data in AngularJS by utilizing the <pre> tag

How can I properly format and display a JSON string inside a dynamically created Div using a forEach loop?

Here is my current code snippet:

<div id="container_div">
</div>

$scope.getJSON = () => {
  var settings = {
    "url": "https://api/json,
    "method": "GET",
    "timeout": 0,
  };
  
  $.ajax(settings).done(function (response) {
    var container = document.getElementById("container_div");
    container.innerHTML = "";
    var content = "";
    response.jsonData.forEach((data) => {
      var json = JSON.parse(data.json);
      var formatted = JSON.stringify(json).split(",").join("<br/>");
      var removeSlash = formatted.split("/").join('replace');
      content += `<div class="col-md-12 shadow p-3 mb-5 bg-white" style="max-height: 500px; overflow-x: auto; overflow-y: auto">
        <p>${JSON.stringify(removeSlash)}</p> </div>`;
      container.innerHTML += content;
    });
    $scope.$apply();
  }).fail(function (error){
    console.log(error);
  });
}

The issue I am currently facing is that the final output div contains unwanted slashes, like this:

"{\"dob\":\"2021-03-17T19:32:24.163Z\"
\"codes\":[]
\"name\":\"Rahul\"}
{\"codes\":[]
\"type\":{\"codes\":[]}
\"name\":\"Rahul\"}]   
\"someDate\":\"2021-03-17T19:42:56.934Z\"}"

I have attempted to remove the slashes using split and join, but without success. How can I fix this issue?

Answer №1

First and foremost, it is essential to parse the response from the server rather than manually iterating through each element.

Additionally, if you are seeing a "/" in your output instead of "/", this could be due to how JSON.stringify handles escaping quotes in a JSON string.

The main issue here lies in the way DOM manipulation is being done. In AngularJS, it is recommended to utilize built-in angular methods instead of searching for elements in the DOM and directly manipulating innerHTML.

angular.module('myApp', [])
  .controller('myCtrl', ['$scope', '$http', function($scope, $http) {
    $http({
      method: "get",
      url: "https://jsonplaceholder.typicode.com/todos"
    }).then(function(response) {
      $scope.todos = response.data;
    })
  }]);
li {
  color: #666;
}

.completed {
  color: green;
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <ul>
    <li ng-repeat="todo in todos" ng-class="{'completed':todo.completed}">{{todo.title}}</li>
  </ul>
</div>

Answer №2

Avoid using JSON.stringify within template strings

let data = "{\"dob\":\"2021-03-17T19:32:24.163Z,\"codes\":[],\"name\":\"Rahul\"},{\"codes\":[],\"type\":{\"codes\":[]},\"name\":\"Rahul\"}],\"someDate\":\"2021-03-17T19:42:56.934Z\"}";
data = data.replace(/,/g, "<br/>");
document.querySelector('body').innerHTML = `<div class="col-md-12 shadow p-3 mb-5 bg-white" style="max-height: 500px; overflow-x: auto; overflow-y: auto">
<p>${data}</p> </div>`;

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

javascript search for parent function argument

I am struggling to figure out how to locate the key in my json array. When I try to find the key using a function parameter, it does not seem to work. This is a snippet of my json data: ... { "product": [ { "title": " ...

Most effective method to avoid updating a node_modules package

tag: After downloading and installing a node_module (npm package)... I have customized the internal files within the node_modules folder to better fit my requirements. Although using it as a node_module is most convenient for me, I am concerned that futur ...

Float and tap

Can someone assist me with my code? I have 4 identical divs like this one, and when I hover over a link, all the elements receive the same code. <div class="Person-team"> <div class="profile-pic-d"> <a cl ...

Generate a new array using a single value extracted from an existing array

I'm new to working with arrays. Before this, I used to manually code everything in HTML. My question is, can you create an array based on the values of another array? var pmmain =["aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", ...

The bidirectional data binding in isolated scope is malfunctioning in AngularJS

I've just started learning angularjs and I'm working with isolated scope. I seem to be having issues with two-way binding using isolated scope. Can someone please review my code and help me debug this issue? When I remove age : '=' from ...

index.js file in npm package optimized for browser compatibility using Babel transpiler

Struggling to create and set up an npm package for use in browser environments, particularly with generating the index file. Currently have the testpackage linked to my test application using npm link in both project directories. The test application is c ...

I'm working on an Angular2 project and I'm looking for a way to concatenate all my JavaScript files that were created from TypeScript in Gulp and then include them in my index

How can I concatenate all JavaScript files generated from typescript in my Angular2 project with Gulp, and then add them to my index.html file? I am using Angular2, typescript, and gulp, but currently, I am not concatenating the javascript files it genera ...

Retrieving columns from JSON using jQuery DataTables

Is it achievable in jquery Datatables to specify columns using a server-side script? I am looking for a solution where the date columns are fetched from the server. It should be able to support varying number of columns. ...

How to locate an element using placeholder in Protractor?

<input _ngcontent-c6="" formcontrolname="password" name="password" onblur="this.placeholder = 'Password'" onfocus="this.placeholder = ''" placeholder="Password" required="" type="password" ng-reflect-required ...

Replacing scrollbars of a div using overflow:auto with arrow indicators: A step-by-step guide

Currently, I am in the process of creating a small div element that will enable users to scroll between images within a jquery image zoom plugin designed for an eCommerce website. Below is the code snippet that I have developed thus far: <div style="w ...

What happens when dynamically loaded static resources are loaded?

Currently, I am dynamically injecting HTML into a page using JQuery AJAX. The injected HTML contains script and link tags for JS and CSS files respectively. The issue I am facing is that my initPage() function runs before the script containing its definiti ...

Having trouble with clearTimeout and clearInterval functions not functioning properly?

Currently, I've set up a countdown using both setInterval and setTimeout functionalities, and it seems to be running smoothly. However, I encounter an issue when trying to stop the countdown upon clicking a certain button; it pauses only after complet ...

Create a personalized edit button for ContentTools with a unique design

I'm struggling to figure out how to customize the appearance and location of the edit button in ContentTools, a wysiwyg editor. After some research, I learned that I can use editor.start(); and editor.stop(); to trigger page editing. However, I want ...

Using Angular 4 constructor value in a condition with *ngIf

Within this TypeScript snippet, there is a variable called moreinfo that is initially set to 1. In the constructor, however, the value of moreinfo is changed to 2. Subsequently, based on whether the value is 1 or 2, different div elements are displayed usi ...

Creating tube-like geometry in intervals using three.js

Is there a way in Tube Geometry(Three.js) to plot and render only a portion of the tube at a time, with the option to continue plotting from that point after a set interval or timer? ...

What is the purpose of deserializing the user for every request using PassportJS?

While I have scoured the official documentation and various online resources, I am still unable to find a solution to what seems like an obvious question. When working with Passport.js, it is necessary to define two methods - one for serializing and one f ...

Using jQuery UI Dialog with pjax for dynamic content loading

I'm currently utilizing pjax within a web application that incorporates jQuery UI dialogs. One issue I've encountered is that the div element responsible for creating the dialog gets displaced from its original container in the DOM once the dialo ...

Leverage the Google Maps JavaScript API v3 to retrieve details for multiple locations using the getDetails(request, callback

I successfully integrated the Google Maps JavaScript API v3 to create a personalized store locator for our company's website. While the current code is functional for two stores, it lacks scalability due to the unconventional methods used. My impleme ...

Sending an array from one page to another with Vue

I'm facing the challenge of passing an array from one page to another. When accessing the next page on form submission using this.$router.push('path'), is there a way for me to also transfer the array so that it can be accessed on the new p ...

How to pass a variable or value through the async await API in the Vue.js and Laravel integration?

I'm facing an issue with my API where I want to check if a given email exists in the database, but every time I run it and view the console log, it returns undefined. Can anyone here suggest a better code snippet or approach for this? I specifically w ...