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

initial render results in undefined data

function Story() { let { id } = useParams(); const pin = useSelector(state => state.pins.pin); const dispatch = useDispatch(); const userid = 2 useEffect(() => { dispatch(getPin(id)); }, [dispatch, id]); return ( <div classN ...

The array is arranged properly, yet React is failing to render it in the correct order

Here's the code snippet I am working with: { this.state.rows.map((qc) => qc.BinsByDayByOrchardsQCs.map((qc2) => qc2.BinsByDayByOrchardsQCsDefects.map((qc3) => !defectsArray.includes(qc3.Defect) &am ...

The code for populating the lookup does not perform as expected on the initial attempt

I've encountered an issue with my JavaScript code on a form where it auto populates 2 lookup fields with the current user when the record is being created. Most of the time, this function works as intended. However, I've noticed that during the f ...

Enhance the current model in backbone.js by incorporating additional data

When a user selects an item on the webpage, more details need to be fetched and displayed. The API function /api/full_details has been implemented to return the additional data for that item. Challenge: How can I retrieve the additional data and append it ...

What is the process for incorporating beforeAnimate and afterAnimate callbacks into a custom jQuery plugin?

Let's imagine I have developed a plugin: // creating the plugin (function($){ $.fn.myPlugIn = function(options){ defaults = { beforeAnimate : function(){}, afterAnimate : function(){} ...

I'm experiencing an issue where my drum app element does not refresh after performing an action dispatch

Struggling with my React/Redux drum app, I'm at a roadblock with the final component that should update with the selected object's ID through an action dispatch. It baffles me why the element won't reflect the changes even though I've c ...

The useEffect hook is not successfully fetching data from the local db.json file

I'm attempting to emulate a Plant API by utilizing a db.json file (with relative path: src\plant-api\db.json), and passing it from the parent component (ItemList) to its child (Item) but I am facing an issue where no data is being displayed ...

Upon the initial data retrieval, everything seems to be working fine. However, when the user transitions to chatting with another user, the state value does not reset and instead shows a combination

Exploring the world of react.js and node.js, I am currently working on developing a chatting application with the integration of socket.io. The issue I'm facing is that when a user clicks on another user to chat, the previous chat messages are display ...

The dynamic JavaScript in Bootstrap 4 seems to be malfunctioning, despite working perfectly in Bootstrap 3

I am currently implementing a dynamic modal feature using the code snippet below: // Show Ajax modal with content $(document).on('click', '[data-modal]', function (event) { event.preventDefault(); $.get($(this).data('moda ...

Can you explain the contrast between img.height and img.style.height?

I'm currently in the process of resizing a series of images by iterating through an array and adjusting their sizes. if(items[0].height > 700 || items[0].width > 700){ items[0].style.height = "700px"; items[0].style.width = "700px"; } As ...

What could be causing the CastError: Cast to ObjectId failed in my code?

Whenever I try to access a specific route in my project, the following error is returned: Server running on PORT: 7000 /user/new CastError: Cast to ObjectId failed for value "favicon.ico" (type string) at path "_id" for model "User" at model.Query.exe ...

What is the impact of sending a JavaScript request to a Rails method every 15 seconds in terms of efficiency?

I have a method that scans for notifications and initiates a js.erb in response. Here is the JavaScript code triggering this method: setInterval(function () { $.ajax({ url: "http://localhost:3000/checkNotification", type: "GET" }); }, 15000); ...

Please elaborate on the appropriate application of angularjs Directives in this specific scenario

From my experience with Angular, I've learned that directives are used for manipulating the DOM while controllers are more about controlling functionality. I've been struggling to convert a small wizard into generic directives, aiming for reusab ...

The getUserMedia() function fails to work properly when being loaded through an Ajax request

When the script navigator.getUserMedia() is executed through regular browser loading (not ajax), it works perfectly: <script> if(navigator.getUserMedia) { navigator.getUserMedia({audio: true}, startUserMedia, function(e) { __ ...

What causes Chrome to automatically remove a script tag?

Hello everyone! Instead of utilizing jQuery, I have been creating a script tag and appending it to the head tag in order to retrieve JSONP data. However, after the JSONP callback function is executed, I have noticed that the script tag that I added to the ...

Video background mute feature malfunctioning

I've searched through numerous resources and reviewed various solutions for this issue, yet I still haven't been able to figure it out. Could someone please guide me on how to mute my youtube embedded video? P.s. I am a beginner when it comes to ...

Saving information to a hidden div using jStorage

Currently, I am utilizing jStorage for storing data in local storage. When I store the data using console.log() and later retrieve it using $.jStorage.get(), I found that the values are not being assigned to the hidden div. Can someone provide guidance o ...

Debug errors occur when binding to computed getters in Angular 2

Currently, I am integrating Angular 2 with lodash in my project. Within my model, I have Relations and a specific getter implemented as follows: get relationsPerType() { return _(this.Relations) .groupBy(p => p.Type) .toPairs() ...

Several different factors

I need to develop a form that allows users to edit existing comments. The form will display a textarea containing the old comment text and a submit button. My goal is to send the newComment data via ajax to another script. However, I am facing an issue w ...

The benefits of installing gulp plugins locally versus globally

Being a newcomer to Gulp, I have a query: should I install gulp plugins (like gulp-sass or gulp-imagemin) locally or globally? Most online examples suggest installing them locally using the --save-dev option. This method saves the modules in the local node ...