Utilizing AngularJS: Transforming JSONP information into HTML

I'm relatively new to utilizing $http and fetching data from various websites. My main query is, how can I convert JSONP into HTML? Specifically, when using $http to request the Atari Wikipedia page, the content is displayed with

and

HTML elements. How can I ensure that the data renders correctly?

var app = angular.module('app', []);

app.controller('DataCtrl', ['$scope', '$http',
  function($scope, $http) {
    // $scope.list;
    var url = 'http://en.wikipedia.org/w/api.php?titles=atari&rawcontinue=true&action=query&format=json&prop=extracts&callback=JSON_CALLBACK';

    $http.jsonp(url).success(function(data) {
      $scope.info = data.query.pages[2234].extract;
    }).error(function(data) {
      $scope.data = "Error";
    });

  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<div id="wrapper" ng-app="app">
  <div ng-controller="DataCtrl">
    <div>{{info}}</div>
  </div>
</div>

Answer №1

If you want to safely display HTML content in Angular, one approach is to use the $sce.trustAsHtml function along with ng-bind-html:

var app = angular.module('app', []);

app.controller('DataCtrl',['$scope','$http', '$sce',function($scope,$http, $sce){
    var url = 'http://en.wikipedia.org/w/api.php?titles=atari&rawcontinue=true&action=query&format=json&prop=extracts&callback=JSON_CALLBACK';

    $http.jsonp(url).success(function(data){
        $scope.info = $sce.trustAsHtml(data.query.pages[2234].extract);
    }).error(function(data){
        $scope.data = "Error";
    });

    }]);

.

<div ng-bind-html="info"></div>

Make sure to review the relevant documentation for further details.

It's important to note that without proper validation and precautions, this method can leave your system vulnerable to security threats like XSS attacks.

Answer №2

If you only want to display the html content, you can utilize the ng-bind-html directive in your page to bind html from a scope variable. However, this also requires the use of $sce.trustAsHtml to sanitize the html. Additionally, you must include the ngSanitize module in your main app module along with angular-sanitize.js

Markup

<div ng-bind-html="trustedHtml(info)"></div>

Controller

app.controller('DataCtrl', ['$scope', '$http', function($scope, $http, $sce) {
    // $scope.list;
    var url = 'http://en.wikipedia.org/w/api.php?titles=atari&rawcontinue=true&action=query&format=json&prop=extracts&callback=JSON_CALLBACK';

    $http.jsonp(url).success(function(data) {
        $scope.info = data.query.pages[2234].extract;

    }).error(function(data) {
        $scope.data = "Error";
    });

    $scope.trustedHtml = function(val){
        return $sce.trustAsHtml(val)
    }

}]);

Answer №3

Although previously discussed, the ng-bind-html directive is effective for displaying data. If you need to manipulate the data in the controller, consider using $sanitize(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

Step-by-step guide to creating a dynamic button that not only changes its value but also

I am trying to implement a translation button on my website that changes its value along with the text. Currently, I have some code in place where the button toggles between divs, but I am struggling to make the button value switch as well. Given my limit ...

Tips for merging two applications into a single file using Node.js

This code snippet represents the functionality of my chat application. var worker = function(worker) { var http = require('http'); var fs = require('fs'); var app = http.createServer(function(request, response) { f ...

Having trouble with IE7 - unable to interact with elements below popup form

<script type="text/javascript">var switchTo5x=true;</script> <script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script> <script type="text/javascript">stLight.options({publisher:'b42661f5-2dc5 ...

Is there a way to adjust the width of a table cell in Material UI using React?

I encountered a problem where I am attempting to adjust the width of a table cell, specifically in Typescript. However, I am only able to choose between medium and small sizes for TableCellProps. Is there a workaround for this issue? I am looking to expand ...

Ajax insertion was successful, but the database records are empty

Why is my code able to save data to the database using Ajax, but all rows are empty? Here is My Form: <form name="frm" id="frm" action=""> <div class="form-group"> <label for="namaproduk">Product Name</label> <input t ...

The ng-change function does not seem to be functioning properly within the UI-select2

Why isn't ng-change firing when I change the selection in the dropdown menu? Here is the HTML and JavaScript code: <ui-select ng-model="DemandLine.SupplierId" theme="select2" ng-change="GetSupplierInfo()"> ...

"Enhancing website performance with JavaScript by leveraging DOM innerHTML scrollHeight

Here is a two-part question I have: The first part of the question: test A: t1 = new Date().getTime(); for (i=0; i<205; i++) { document.getElementById("divTest").innerHTML = sText; } t2 = new Date().getTime(); ...

Is there a way to efficiently process multipart/formdata, application/json, and text/plain within a single Express handler?

Operating an express demo server that mirrors the client's POST requests back to it is a part of an educational practice. In this exercise, the client makes a POST request using the fetch API, like so: fetch('http://localhost:5000/', { m ...

React Navigation Bar Links Fail to Show Content

I'm a beginner in the world of React and I could really use some assistance. Right now, I am working on creating a portfolio using React and focusing on the Nav component. Although I haven't encountered any errors in the Console, when I click on ...

Enhancing UI design with Vue.js

I'm attempting to customize elements using data from a JSON file in Vue.js: <div v-for="(item, index) in json._items" class="help-inner-callout" v-html="item.text" style="top:item.top; left: item.left;">&l ...

AngularJS - The requested header field is not permitted by the preflight response of Access-Control-Allow-Headers

I'm currently utilizing the library https://github.com/doedje/jquery.soap/ to establish a connection between an Ionic application and an ASMX web service. However, I've encountered an issue: When attempting to connect to , I receive the f ...

How do I retrieve the download URL for the file created using Python in my Heroku App?

After developing my Flask App, I uploaded several files to the Heroku filesystem. I'm aware that these files are removed every time the dyno restarts. Now, in my HTML/JavaScript frontend, I'd like to provide users with a download button for thes ...

Attempting to retrieve XML/JSON

I am struggling with extracting the first 15 words from a file using the API. I have attempted to do it with both XML and JSON, but keep encountering this error: XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on th ...

Transforming DOM elements into Objects

Here are some values that I have: <input name="Document[0][category]" value="12" type="text"> <input name="Document[0][filename]" value="abca.png" type="text" > I am looking for a way to convert them into an object using JavaScript or jQuer ...

Encountering an issue when trying to upload a file for the second time

I am currently working on a project where I need to upload an excel file and send it to an API using ReactJS. So far, I have been able to successfully send the file to the API. However, in my submit function, I want to reset the saved excel file from the s ...

Attempting to generate a fresh document by duplicating the data from a specific variable

Currently attempting to generate a new csv file within a specific directory. The goal is to save the data of a variable inside the created csv file: handleRequest(req, res) { var svcReq = req.body.svcReq; var csvRecData = JSON.stringify(req.bod ...

Implementing a feature in ReactJS that allows users to upload multiple images in base64 format

I'm trying to develop an image uploader using base64 and I want the output as an array. However, I am encountering an issue where the array is coming out empty!. I suspect it might be due to an asynchronous problem. Any tips on how to incorporate asyn ...

Tips for arranging bar series in the NVD3 multibar angularJS directive

I am trying to generate a multi-bar chart using the nvd3 AngularJS directive by cmaurer, but I am facing an issue with stacking some series. Here is the data I am working with: $scope.exampleData = [ { "key": "Initial ...

Dividing the code into a function and invoking it does not produce the desired outcome

Everything seemed to be working perfectly until I attempted to encapsulate the code into a function and call it within my expression. Unfortunately, this approach did not yield the desired results. Functional code: render: function() { return ( ...

The submit option fails to appear on the screen in the JsonForm library

I've been using the JsonForm library ( https://github.com/jsonform/jsonform ) to define a form in HTML. I have set up the schema and form of the JsonForm structure, but for some reason, the "onSubmit" function that should enable the send button is not ...