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

Randy Strauss
  • 93
  • 1
  • 7
  • did you try ng-bind-html="varInScope", and storing the return of renderHtml into varInScope ? – Gonzalo.- Mar 27 '17 at 02:22
  • 2
    Possible duplicate of [AngularJS : Insert HTML into view](http://stackoverflow.com/questions/9381926/angularjs-insert-html-into-view) – Gonzalo.- Mar 27 '17 at 02:22

3 Answers3

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.

The.Bear
  • 5,621
  • 2
  • 27
  • 33
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>

Luis Estevez
  • 1,387
  • 12
  • 19
  • 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. – Randy Strauss Apr 02 '17 at 18:54
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>
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
  • 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:
    – Randy Strauss Apr 02 '17 at 18:55