Randy Strauss
Randy Strauss

Reputation: 93

Can't inject HTML into an angular page

I want to inject html into an angular page

My controller starts with:

myapp.controller("myCtrl", function ($scope, $http, $stateParams, $sce) {

$scope.renderHtml = function(html_code) {
    return $sce.trustAsHtml(html_code);
};
$scope.pgf = "<p>Hello</p>";

And on my HTML page I have:

<div class="intro"> AA {{renderHtml(pgf)}} AA </div>

And in the browser, I see:

AA <p>Hello</p> AA

Where what I want is

AA
Hello
AA

Is this a version problem- how do pick a consistent set of versions? (If I just raise the versions, I get all sorts of errors...)

Upvotes: 1

Views: 925

Answers (3)

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27192

Try ngBindHtml directive in module ng. It provides a secure way of binding content to an HTML element.

Syntax :

<element ng-bind-html="expression"></element>

DEMO

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

app.controller('MainCtrl', ['$scope', '$sce', function($scope, $sce) {
  $scope.renderHtml = function(html_code) {
    return $sce.trustAsHtml(html_code);
  };

  $scope.pgf = "<h1>Hello I'm a Bear</h1>";
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainCtrl">
  <div ng-bind-html="renderHtml(pgf)"></div>
</div>

Upvotes: 1

The.Bear
The.Bear

Reputation: 5855

You have to use ng-bind-html (angular ngBindHtml docs) to bind HTML content...

CONTROLLER

function myCtrl($scope, $sce) {

    $scope.renderHtml = function(html_code) {
        return $sce.trustAsHtml(html_code);
    };

    $scope.pgf = "<p>Hello I'm a Bear</p>";
}

HTML

<div ng-bind-html="renderHtml(pgf)"></div>


Additionally, here you are a working PLUNKER with your example.

Upvotes: 2

Luis Estevez
Luis Estevez

Reputation: 1407

So your Angular code works but you didn't place your html binding in the right place. You can't set a function inside angular binding {{ function }}

So in your HTML should say <div ng-bind-html="trustHTML(pgf)"></div>

Upvotes: 1

Related Questions