我使用AngularJS v1.4.2并喜欢从$scope
中的变量打印html。
我尝试使用ng-bind-html
和ng-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>
...
答案 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