AngularJS v1.4.2 ng-bind-html和ng-bind-html-unsafe不起作用

时间:2015-07-15 12:36:10

标签: javascript angularjs ng-bind-html

我使用AngularJS v1.4.2并喜欢从$scope中的变量打印html。

我尝试使用ng-bind-htmlng-bind-html-unsafe,但两者都无效。

这是我的控制器:

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>";
        });

我的HTML代码:

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

3 个答案:

答案 0 :(得分: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>


确保在应用中包含 angular-sanitize.js 并注入 ngSanitize 模块,并在控制器中注入 $ sce

答案 1 :(得分:0)

有必要使用$ sce(Strict Contextual Escaping service

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

答案 2 :(得分:0)

根据ng-bind-html的文档,您需要将ngSanitize添加到您的模块依赖项中,以使其正常工作,看起来您没有;)

查看https://docs.angularjs.org/api/ng/directive/ngBindHtml上的示例以获取更多详细信息。

干杯 d