A guide on linking HTML information within a JSON attribute in Angular

This is an example of my JSON data:

[
  {
    "Title": "MyTitle1",
    "Content": "<p>Content1</p>",
    "Date": "2014-11-19T10:00:00"
  },
  {
    "Title": "MyTitle2",
    "Content": "<p>Content2</p>",
    "Date": "2014-11-19T00:00:00"
  }
]

Within my controller, I retrieve the JSON like this:

app.controller('NewsfeedCtrl', function ($scope, $http) {
    $http.get(serverAddress + '/api/newsfeed/page/1').
      success(function (data, status, headers, config) {
          $scope.newsfeeds = data;
      }).
      error(function (data, status, headers, config) {
          console.log("Something went wrong.");
      });
});

I then display it in the view like this:

<div ng-controller="NewsfeedCtrl">
    <div ng-repeat="newsfeed in newsfeeds">
        {{newsfeed.Title}}
        <br />-
        <br />{{newsfeed.Date}}
        <br />-
        {{newsfeed.Content}}
    </div>
</div>

However, if there are HTML tags within the Content, how can they be properly displayed in the view while also being parsed?

Answer №1

Utilize the ng-bind-html directive to manage content as HTML content.

<div ng-controller="NewsfeedCtrl">
    <div ng-repeat="newsfeed in newsfeeds">
        {{newsfeed.Title}}
        <br />-
        <br />{{newsfeed.Date}}
        <br />-
        <div ng-bind-html="newsfeed.Content"></div>
    </div>
</div>

Additionally, remember to add the ngSanitize module to your application like this.

angular.module('itadPortal', ['ngRoute', 'ngSanitize']);

To learn more about ng-bind-html, click HERE.

Answer №2

Utilizing the ngBindHtml directive:

<span ng-bind-html="newsfeed.Content"></span>

Answer №3

To improve the loading speed of the HTML tags within the Content section, it is advisable to replace them with a placeholder name (for example, "Content2") and then include them inside a p tag. In this way, your JSON structure would be as follows:

[
  {
    "Title": "MyTitle1",
    "Content": "Content1",
    "Date": "2014-11-19T10:00:00"
  },
  {
    "Title": "MyTitle2",
    "Content": "Content2",
    "Date": "2014-11-19T00:00:00"
  }
]

Ensure that your view incorporates this line:

<p> {{newsFeed.content}} </p>

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 best way to create a button with this functionality?

In the form that I have created, it is opened in a bootstrap modal style. This form contains a button that, when clicked, triggers an alert box to appear. The code snippet used for this functionality is as follows: echo "<script>"; echo "alert(&apos ...

Next Value in Array Following Selected One

Apologies for the repetition, but despite my attempts, I haven't been able to find a solution that works for me. When a user clicks on an element, I need to retrieve the following information: The ID of the selected element An array containing all v ...

Solving a web API error: Steps to fix issues with your web

Having trouble diagnosing the error I'm encountering in my new project. Even though I've replicated the setup from my previous projects, something seems off. Any guidance on what might be wrong? Error Message $id: "1" Message: "No HTTP ...

Missing callback pattern in NodeJS

When I spend hours writing NodeJS code, there's a common scenario that leaves me unsure of how to proceed. Take the following async function call (where we forget the necessary callback): function foo (callback) { // Perform a task and call callba ...

Checkbox fails to display as checked

I am currently working on implementing checkbox inputs in React JS. I have encountered an issue where the checkboxes do not visually show as checked when clicked, but I am still able to retrieve the value of the checkbox. Here is my code: Simple Checkbox I ...

Click outside to toggle dropdown and hide it

My dropdown menu is currently working, but I would like it to close when I click outside of it. I've tried various solutions provided in other posts, but I just can't seem to get it right. Can someone please help me figure out what I am missing? ...

Is there a way to stop Chrome from creating an endless loop while showing alerts during the focus event, without having to disable and enable the event repeatedly?

Looking for a solution to prevent an infinite loop of alert messages in Google Chrome when clicking on cmbMonkeys. The workaround for cmbPeople is working fine, but I'm curious if there's another way to handle alerts on focus or blur events with ...

How to display (fade in a portion of an image) using .SVG

I have the following code in my DOM: <div class="icon-animated"><img src="icon_non_active.svg" id="icon_non_active"></div> There are two icons (.svg) available: icon_non_active & icon_active Can I animate the transformation from i ...

When the template is loaded, the AngularJS radio button does not reflect the checked status based on

Is there a way to automatically check the correct radio button based on the value of fc.confidence when the template initially loads? Even when the value of fc.confidence is None, the code provided below does not select either radio button. div.contai ...

Storing the state of a checkbox as either 0 or 1 in the database via an Ajax POST request

My database has several columns configured as TINYINT and an equal number of checkboxes on the front end. Below is my HTML code: <script type="text/x-handlebars" id="project"> <div class="row"> <div class="span6"> ...

Looking to fetch FritzBox log files on Raspberry Pi using Python's 'wget' subprocess, but receiving HTML data instead of JSON

My goal is to retrieve event and WLAN logs from my AVM FritzBox 7350 router (OS 7.57) in JSON format using a Python 3 script. Surprisingly, while the script works perfectly on my ArchLinux machine, I only receive an HTML file when running it on my Raspberr ...

Verify if there are any new updates to a JSON file on the web and then analyze it against a file that is

Currently, I am exploring the depths of a dense forest: I possess a universal app with navigation capabilities that showcases data stored in a plist file. For my next update, I aim to transition the database to a JSON file hosted on my server. The app will ...

Clear the previously displayed scene in Three.js

After setting up a renderer scene in threejs, I encountered an issue when trying to load a model for the second time. I'm looking for a way to clear the previous rendered scene from the canvas. Is there a solution available within threejs? ...

achieve precise outcomes using mapping techniques

I am currently learning react.js and encountering an issue with obtaining specific results on the map. Below is the code I am working with: render(){ const friends = [ {id:1, name: 'Dave',age:50}, {id:2,name: 'Kellie',age:42}, {id:3, ...

Retrieving data from an external PHP script

I'm facing an issue with retrieving results from a PHP file after submitting a form: index.php (located at ) <form id='loginForm' action='http://domain1.com/mail.php' method='POST'> <input id=&apo ...

Show component featuring checkboxes

Is it possible to show a component when a checkbox is clicked? I am creating a dashboard and need to choose which tools to display on my screen. I have set up checkboxes with v-model="select", value="name of component", and used v-for for list rendering. ...

How can I import an excel spreadsheet using Javascript, or alternatively, convert an excel file to a text document

I have been updating my file upload page to handle both text and excel files. However, when trying to read excel files with my current code, I am getting strange output. It seems that my function, which was originally designed for text files, needs modific ...

Unable to retrieve the value from a textarea when using Shopify Product Options by Bold

I'm currently facing an issue trying to retrieve the value of a textarea using Shopify's Product Options by Bold. The code works fine locally, but when I transfer it over to Shopify, I am unable to get the value. Despite looking at various resour ...

The autofocus feature on the textarea in Angular Material Dialog seems to be malfunctioning

Within a web app, I am utilizing the Dialog component from Angular Material. The Dialog consists of only a textarea that is initially empty. I aim to automatically focus on the textarea when the user opens the modal dialog. How can I achieve this? Despite ...

What is the best way to implement a shared function across two classes?

I have a jQuery code that works as intended with the .foto class. Now, I need to add the .fotoleft class to perform the same function. How can I make the function work for two different classes? $(document).ready(function() { $(".foto").click(functi ...