Can Angular be used to display standard HTML tags?

Is it possible to display HTML tags (text with anchors) stored in the $scope variable on the output view? Take a look at this example. I'm facing an issue where the anchors from my database are sometimes hidden within the text. Thank you for any assistance! :)

Sample HTML:

<div ng-app>
  <h2>Html test</h2>
  <div ng-controller="TodoCtrl">
    <p data-ng-repeat="line in anchors">
      {{line}}
    </p>
  </div>
</div>

Controller Logic:

function TodoCtrl($scope) {
  $scope.anchors = [
    "<a href='#'>Something</a>", 
    "Angular ignores html tags :("
  ];
}

Answer №1

Indeed, it is potentially achievable through the utilization of the ng-bind-html directive

angular.module('application',['ngSanitize'])
.controller('TaskCtrl',
function TaskCtrl($scope) {
  $scope.links = ["<a href='#'>Something</a>", "Angular does not overlook html tags :)"];
});
h2 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-sanitize.js"></script>
<div ng-app="application">
  <h2>Testing Html</h2>
  <div ng-controller="TaskCtrl">
    <p data-ng-repeat="item in links" ng-bind-html="item">
      
    </p>
  </div>
</div>

Answer №2

Incorporating the HTML once it has been marked as trustworthy allows for its injection into the DOM using ng-bind-html.

angular.module('myApp', [])
  .directive('myDirective', function($sce){
    return {
        link: function(scope) {
          scope.trustedHTML = $sce.trustAsHtml('<h1>This is html</h1><h2>Subtitle</h2>');
        }
    }
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.js"></script>

<div ng-app="myApp" my-directive>
    <div data-ng-bind-html="trustedHTML"></div>
</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

The collaboration between NextAuth and Firebase is resulting in a SyntaxError that prohibits the use of import statements outside

As a beginner in both Next.js and Firebase, I have been attempting to utilize NextAuth.js for authentication with Discord on my firebase application. Unfortunately, I encountered an error.https://i.sstatic.net/2mfJK.png Despite adding "type": "module" to ...

Is there a way to reach the public functions within a module from a private method?

I'm facing a very annoying issue. How can I access the public module function from inside a private module pattern? I've left a comment on the problematic line...is there any workaround for this? angular.module("myApp").factory('models&apos ...

What makes componentDidMount the ideal location to initiate AJAX requests?

It is quite common to see AJAX requests being fired at the componentDidMount hook in many React projects. However, I find it hard to understand this suggested practice. For example, consider a component where the AJAX request depends on a prop from the pa ...

How can I use React Native to align two text tags differently within the same row?

In this particular scenario, I attempted to showcase two distinct elements within a list item. However, I encountered a challenge in figuring out how to display the "item.date" on the left side of the line, and the string "Click to show.&qu ...

What is the method of adding a child to the outerHTML of the parent element instead of within it?

Is there a way to use the outerHTML method on a parent element to append a child element so that the icons appear outside of the targeted element rather than inside it? The current code snippet shows the icons inside the box, but I want them to be placed o ...

Encountering the "TypeError: Unable to access property 'indexOf' of undefined" error while utilizing the ipfs-api

During my development work with the ipfs-api, I ran into an issue where adding an image file to the ipfs node was not functioning properly. Upon further investigation into the error details, it appears that the protocol is being treated as undefined in the ...

AngularJS collapsible data row is a powerful feature that allows users to easily

I am looking to present parent and child related data in an expandable format without relying on panels. Example: <div ng-app="app" ng-controller="customersCtrl"> <table st-table="rowCollection" class="table table-striped"> &l ...

Click to remove the ellipsis from the backbone

Some Background Info I am working on creating a feed similar to Twitter where each row expands on click to show more information. The data is fetched from a JSON file sent from the backend to the frontend, and I am using Backbone.js for rendering. My fee ...

Protractor: refreshing non-angular login page

Currently, I am experimenting with an angular webpage. However, before proceeding, I need to log in on a non-angular page that redirects to another non-angular one. Upon trying to execute my test by entering the username and password, the page unexpectedly ...

Tips for displaying personalized error messages from your REST API in a JavaScript client

I'm utilizing a Java REST API that has been generated using swagger. If the client is unauthorized, I am sending custom error messages in response. public Response collaborationCollabIdDelete(Integer collabId, SecurityContext securityContext, Str ...

What are the best methods for testing REST API and Client-side MVC applications?

When dealing with a RESTful server that only responds with JSON data fetched from a database, and having a client-side application like Backbone, Ember or Angular, where should application testing take place? Is it necessary to have two sets of tests - on ...

Unlocking the JSON array of data in JavaScript: A step-by-step guide

Hey there, I need help extracting an array from a JSON data structure. Here's an example of my JSON object: { Data1 : { Data2 : "hello", Data3 : "hi" }, Data4 : { Data5 : "this is Karan", } } I'm looking ...

Apply a jQuery class to six randomly selected elements that share the same class attribute

I have a total of 12 elements that all have the "block" class, and I am looking to randomly assign the "active" class to exactly 6 out of the 12 elements. My initial thought was to use a for loop to achieve this task, but I'm unsure about how to go a ...

Passing data as a parameter from the view to the controller using AngularJS

I am attempting to retrieve data from a view, which must be passed as a parameter in a function in order to populate an array in the controller. However, I am not receiving any objects in return. Here is what I have tried: VIEW <div ng-repeat="cssfram ...

What is the proper way to utilize the setState() function in ReactJS?

I am new to the world of ReactJS and I have been exploring the concepts of state and setState(). While trying to implement a name change using setState(), I found myself wondering where exactly in my code should I invoke the setState() method: Should I c ...

The size of the card image and content area will remain constant based on the specified percentage

Looking for some guidance as I am still learning. I need the card below to have a fixed width of 38% for the image area and 62% for the content area, regardless of the size of the content (the height can increase if there is more text). In the image above ...

Using TypeScript to Verify the Existence of Words in a String

Is there a way in typescript to find specific words within a given string? For example: If we have a list: ['Mr', 'Mrs', 'FM.', 'Sir'] and a string named 'Sir FM. Sam Manekshaw'. The words 'Sir' ...

What is the best way to sort items by their properties?

Seeking to optimize the code by using a filter instead of lodash _forEach. However, the current filter code is not producing the desired result. Any insights on what might be incorrectly implemented here? main.js ...

Experience the feeling of releasing momentum by click and dragging the scroll

One feature I am looking for is the ability to control the scroll speed when dragging, and have the scroll continue moving slightly after release instead of stopping instantly. CodePen: https://codepen.io/rKaiser/pen/qGomdR I can adjust the speed adequat ...

Leverage the power of CSS and jQuery's calc function within your React.js

Currently, I am facing a situation where I require the div to have a dynamic width in my React JS code. To achieve this, I tried using divStyle = {width: calc(100% - 276px)}, but unfortunately, it resulted in an error stating that calc is not a function. ...