How to embed HTML using Angular 1.4?

I have a data source that contains an array of raw HTML strings. I have to display them on the page to the user.

Being a little new with Angular, the first thing I tried was this:

<div ng-repeat="html in ctrl.html" ng-bind="html"></div>

This causes Angular to leave my HTML code and display it as a string. This is not what I need, but at least it shows that Angular is really loading data.

When doing a Google search, I read about the ng-bind-html-unsafe directive, which, as I understand it, should enter text into an HTML document, without avoiding or sanitizing it in any way that I want, because I have to trust our data source.

<div ng-repeat="html in ctrl.html" ng-bind-html-unsafe="html"></div>

This does not work either. It just shows me a blank page. When I open the document inspector, I see that for each entry in the HTML array there is a div tag, but all fields are empty.

By doing more of Google-fu, I found discussions about method calls in $ scope to make Angular good with this. They say that ng-bind-html-unsafe is deprecated.

With all the talk about different ways to do what I need with different versions of Angular, how to do it with today's version: 1.4?

+4
source share
3 answers

I think you need to "sanitize" your html's.

Example:

angular.module('sanitizeExample', ['ngSanitize'])
       .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
         this.html = array with your htmls;

         this.sanitizeHtml = function(html) {
           return $sce.trustAsHtml(html);
         };
       }]);

Then

<div ng-repeat="html in ctrl.html" ng-bind-html="ctrl.sanitizeHtml(html)"></div>

I think it will work

+6
source

use the ngSanitize module ...

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

see this link. this work is beautiful

+1

<div ng-repeat="html in ctrl.html" ng-bind-html="ctrl.sanitizeHtml(html)"></div>

myApp.filter('unsafe', function($sce) { return $sce.trustAsHtml; });

-1

Source: https://habr.com/ru/post/1606822/


All Articles