1

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>
...
2
  • 1
    "Don't work"? Are you getting any errors? Commented Jul 15, 2015 at 12:39
  • 2
    HTML content in variables has to be trusted, else the HTML is stripped out. use the $sce to trust your HTML content. see docs.angularjs.org/api/ng/service/$sce Commented Jul 15, 2015 at 12:41

3 Answers 3

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

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

Comments

0

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.