Thomas Kaemmerling
Thomas Kaemmerling

Reputation: 547

AngularJS v1.4.2 ng-bind-html and ng-bind-html-unsafe don't work

I'm using AngularJS v1.4.2 and like to print out html from a variable in the $scope.

I tried to use ng-bind-html and ng-bind-html-unsafe but both are not working.

Here is my controller:

var ctrl = angular.module('app.ctrl',['app.model'])
        .controller('Controller',function($scope, $log, Model){
            $log.warn("controller für View wurde erstellt");
            $log.log(Model.getValue());
            $scope.sayHello="Hello World!";
            $scope.sayHelloHtml="<strong>Hello World Fett</strong>";
        });

And my HTML code:

...
<div ng-controller="Controller">Meine erste angularJS View {{ sayHello }}
<div ng-bind="sayHello"></div>
<div ng-bind-html="sayHelloHtml"></div>
</div>
...

Upvotes: 1

Views: 160

Answers (3)

Damiano Ferrante
Damiano Ferrante

Reputation: 151

according to the docs for ng-bind-html you need to add ngSanitize to your module dependencies for it to work correctly, which looks like you didn't ;)

Check the example on https://docs.angularjs.org/api/ng/directive/ngBindHtml for further details.

Cheers D

Upvotes: 0

Marco Talento
Marco Talento

Reputation: 2395

It's necessary to use the $sce (Strict Contextual Escaping service)

$scope.sayHelloHtml = $sce.trustAsHtml("Hello World Fett");

Upvotes: 0

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

var ctrl = angular.module('app.ctrl',['app.model','ngSanitize'])
        .controller('Controller',function($scope, $log, Model,'$sce'){
            $log.warn("controller für View wurde erstellt");
            $log.log(Model.getValue());
            $scope.sayHello="Hello World!";
            $scope.sayHelloHtml="<strong>Hello World Fett</strong>";

            $scope.sayHelloHtml = $sce.trustAsHtml($scope.sayHelloHtml);
        });

HTML

 <div ng-controller="Controller">Meine erste angularJS View {{ sayHello }}
            <div ng-bind="sayHello"></div>
            <div ng-bind-html="sayHelloHtml"></div>
            <div ng-bind-html-unsafe="sayHello"></div>
            </div>


Make sure you have include angular-sanitize.js and injected ngSanitize module in app and injected $sce in your controller.

Upvotes: 3

Related Questions