1

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...)

2
  • did you try ng-bind-html="varInScope", and storing the return of renderHtml into varInScope ? Commented Mar 27, 2017 at 2:22
  • 2
    Possible duplicate of AngularJS : Insert HTML into view Commented Mar 27, 2017 at 2:22

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This works, but so does (for me) without the function call: <div ng-bind-html="pgf"></div>
1

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>

1 Comment

Thanks! This works, but the trustHTML() function is not needed. That is, it works with and without wrapping the inserted html. The key is to put it in the ng-bind-html attribute.
1

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>

1 Comment

Thanks! This works, but the trustHTML() function is not needed. That is, it works with and without wrapping the inserted html. The key is to put it in the ng-bind-html attribute. This works: <div ng-bind-html="pgf"></div>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.