ng-bind-html与样式不起作用

时间:2017-04-05 11:15:58

标签: angularjs


我正在搜索如何用 ng-bind-html 解决我的问题 作为输入,我想例如一个带有html的图标

icon: '<i class="fa fa-sign-out"><i>'

这适用于 ng-bind-html:

let buttonIcon = angular.element(`<span ng-bind-html="icon"></span>`);

,显示如下:

enter image description here

但是我试图将红色添加到fa-icon

icon: '<i class="fa fa-sign-out" style="color:red;"><i>'

但没有成功

所以我查看了HTML,似乎style="color:red;"不在那里。

但我不会那样显示:

(我尝试在开发工具中添加样式以查看它是否有效)

enter image description here

问候

1 个答案:

答案 0 :(得分:3)

使用$sce.trustAsHtml ..

https://docs.angularjs.org/api/ng/service/ $ SCE

(function(angular) {
  'use strict';
angular.module('myApp', ['ngSanitize'])
  .controller('ctrl', ['$scope','$sce', function($scope,$sce) {

$scope.uCanTrust = function(string){
return $sce.trustAsHtml(string);
}
$scope.Stack = '<i class="fa fa-stack-overflow" style="color:#0077dd;font-size:34px" aria-hidden="true"></i>';
$scope.icon= $sce.trustAsHtml('<i class="fa fa-stack-overflow" style="color:red;font-size:34px" aria-hidden="true"></i>');
    $scope.trustme= $sce.trustAsHtml('<a href="#" style="color:red">Click Me!</a>');

    
  }]);
})(window.angular);
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
  <script src="//code.angularjs.org/snapshot/angular-sanitize.js"></script></head>
<body ng-app="myApp">
  <div ng-controller="ctrl">
 <p ng-bind-html="trustme"></p>
 <p ng-bind-html="icon"></p>
 
 <p ng-bind-html="uCanTrust(Stack)"></p>
</div>
</body>
</html>