What is the best way to display the HTML content being received from the database in the DOM?

I have received an object in this format

[
  {
    "BET": 57630343,
    "CUSTOMER": 181645,
    "SPORT": "MLB",
    "XX_FILL OPEN": "<button class=\"btn\" onclick=\"fillOpen(57630343)\">Fill Open</button>",
    "XX_VIEW": null,
    "XX_CANCEL": "<input type=\"checkbox\" name=\"sports\" value=\"soccer\"  onchange=\"fillOpen(57630343)\"/>"
  },...]

Currently, when rendering this object in the DOM, it appears as shown in the image below:

https://i.sstatic.net/zPxyt.png

The HTML code for the dynamic table is as follows:

      <table>
        <thead>
          <tr>
            <th ng-repeat="column in cols" ng-init="isXX = column.indexOf('XX') === 0">
              <span ng-if="isXX">{{column.substring(3).replace('_', ' ')}}</span>
              <span ng-if="!isXX">{{column}}</span>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr ng-repeat="row in rows">
            <td ng-repeat="column in cols">
              <span>{{row[column]}}</span>
            </td>
          </tr>
        </tbody>
      </table>

The corresponding Angular code is:

    ReportsFactory.pendingBets(reportParam).then(function(data) {
      if (data.length) {
        gridInfo = _.forEach(data, function(item) {return item;});
        $scope.rows = gridInfo;
        $scope.cols = Object.keys($scope.rows[0]);
      }
    }

The database personnel are providing me with the data in the JSON structure mentioned above.

My question is, how can I properly render these elements in the DOM?

Answer №1

If you need to display HTML content in AngularJS, consider using the ngBindHtml directive.

<tbody>
  <tr ng-repeat="row in rows">
    <td ng-repeat="column in cols" ng-bind-html="row[column]">
    </td>
  </tr>
</tbody>

When retrieving HTML from a $http call, it's important to use $sce.trustAsHtml to securely display this HTML within your application:

$scope.rows.forEach(function(row) {
    for (var key in row) {
        if (key.indexOf('XX') === 0) {
            var value = row[key];
            if (value) {
                row[key] = $sce.trustAsHtml(value);
            }
        }
    }

});

To see an example in action, check out this plunkr: http://plnkr.co/edit/7iFUhjg6Q0YIwRi47fDm?p=preview

Answer №2

To achieve this, you can utilize ngSanitize for AngularJS.

For more detailed information, please refer to this link: https://docs.angularjs.org/api/ngSanitize

Another method is using the ng-bind-html directive, which allows you to render HTML code within a DOM element.

In addition, you can incorporate JavaScript within the element by utilizing the trustAsHtml method from the $sce service.

I have created a demonstration example that showcases these concepts. http://plnkr.co/edit/sTEUIWHwGXSAUSQ2rC8y?p=preview

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

Ways to restrict the input of only a single value when writing data using Firebase security guidelines

I'm feeling a little lost when it comes to understanding Firebase security rules - specifically about the concept of working from the top-down according to the documentation. Here is the rule that's causing me some confusion: "rules": { " ...

Creating React elements dynamically with material-ui can be done by utilizing state expressions in properties. This allows for the generation

Within a functional component, I aim to dynamically generate material-ui context menus by utilizing a state object: let legendContextMenuStatesObject = {}; for (let key of keys) { legendContextMenuStatesObject[key] = initialState; } const [lege ...

Sending data with React using POST request

Currently in my React application, I have a form that includes fields for username and password (with plans to add "confirm password" as well). When submitting the form, I need it to send JSON data containing the email and password in its body. The passwo ...

Retrieving a local variable within an AngularJS controller

Examining the code provided below: app.controller('Controller', function($scope, $http){ $scope.rep = []; $scope.tot = { name: '', marketValue: 0, cash: 0, legend: 'none' }; ...

Testing the full stack in AngularJS applications

Is there a way to conduct comprehensive full stack testing for a nodejs/angularjs application? Lately, I have been facing issues with zombiejs where the test results are inconsistent. I am looking for testing methods that replicate user interactions (simi ...

Selecting Texture Coordinates

My goal is to pinpoint where a user has clicked on a texture of an object to trigger a response by redrawing the texture. I've been able to achieve this by rendering my objects with a color-coded texture onto a separate render target and using gl.rea ...

Exploring Head-Linked/Off-center View in Three.js

I'm attempting to create a permanent head-coupled perspective without relying on the full headtrackr library. My head will remain stationary, but it will not be directly facing the screen. For those interested, I have a small demonstration available ...

Is there a way to adjust the height of one div based on the height of another div in Bootstrap?

I am experimenting with a Bootstrap example featuring a table in the left column and 4 columns in 2 rows in the right column. Check out the code below: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css ...

Pass the code from the webpage to the PHP script

On my website, I have implemented a feature using JavaScript that dynamically changes the page content. Now, I am looking for a way to send this updated content to a PHP script. How can I achieve this functionality? ...

Struggling to send data to Wufoo API using PHP and AJAX

I'm still getting the hang of PHP and attempting to send data to a Wufoo Form that includes the fields shown below: https://i.sstatic.net/yoOgy.png However, when trying to POST information to it, I keep receiving a 500: Internal Server Error along w ...

Troubleshooting: Issues with JQuery validation for cross-domain URLs

I'm fairly new to using JQuery and I have a specific requirement which involves validating a link from another domain. If the validation is successful, I need to redirect (open the page in a new window) to that link. Otherwise, I should display an ale ...

The intended 'this' keyword is unfortunately replaced by an incorrect '

Whenever the this keywords are used inside the onScroll function, they seem to represent the wrong context. Inside the function, it refers to the window, which is understandable. I was attempting to use the => arrow notation to maintain the correct refe ...

Is it possible to organize words with HTML elements utilizing JavaScript?

Code is not properly sorting the elements var element='<p><strike>Mango</strike></p>/n<p><em>Orange</em></p>/n<h1>Apple</h1>/n<p><strong>banana</strong></p>/n<p& ...

Implementing image caching in tvOS with React-Native: A step-by-step guide

Looking to Implement Image Caching in tvOS using React Native I'm trying to figure out how to cache images that I download from the internet on my Apple TV. I've experimented with various libraries, but none seem to be compatible with tvOS. Any ...

Exploring the power of Vue.js with dynamic HTML elements and utilizing Vue directives within Sweet Alert

new Vue({ el: '#app', data(){ results: [] } }); I need assistance with implementing Vue directives, events, etc. within the markup of a Sweet Alert. The goal is to display an alert using Sweet Alert that include ...

Obtaining data with jQuery.Ajax technology

I am attempting to retrieve real-time data from a different URL and display it in a text field every second without refreshing the entire page. The content of the URL is constantly changing, so I want the field to update accordingly. However, despite my ef ...

Issues with Angular2 causing function to not run as expected

After clicking a button to trigger createPlaylist(), the function fails to execute asd(). I attempted combining everything into one function, but still encountered the same issue. The console.log(resp) statement never logs anything. What could be causing ...

Arrange the object's key-value pairs in ng-repeat by their values

I'm completely new to AngularJS and I am working with an API that returns key-value pairs related to different sports. $scope.sports = { 1: "Soccer", 2: "Tennis", 3: "Basketball" ... }; My challenge is sorting these items by sport name: <ul> ...

Currently dealing with a script that utilizes AJAX GET to incorporate JSON data into my table

Greetings and thank you for taking the time to read this! Within my HTML, I have implemented a form element that allows inputting data into 5 different fields. This data is then transmitted to a database using my unique API key. Once stored in the database ...

Is it feasible to utilize VAST for delivering HLS streams? Can m3u8 files be incorporated into VAST tags for delivery?

We are integrating a video player that supports VAST pre-roll, mid-roll, and post-roll video ads. I'm wondering if it's feasible to include m3u8 files in VAST tags? I've reviewed the vast specification and examples, but haven't come ac ...