$ sce.trustAsHtml无效?

时间:2018-03-26 13:01:52

标签: javascript angularjs html5 uialertview

我有一个如下警告:

$scope.addAlert('danger', $sce.trustAsHtml('Invalid Alias Name: Certain 
limitations apply to alias naming. <a href="http://google.com/">Please refer 
to the documentation</a>'));

我将这个绑定到html页面:

 <uib-alert ng-repeat="alert in alerts" type="{{alert.type}}" 
 close="closeAlert($index, alerts)" dismiss-on-timeout="2500">
            <span ng-bind-html="alert.msg"></span>
        </uib-alert>

结果, 实际输出:

    Error: Invalid Alias Name: Certain 
    limitations apply to alias naming. '<a href="http://google.com/">Please 
    refer to the documentation</a>'

预期输出     错误:别名无效:某些         限制适用于别名命名。 'Please refer to the documentation'

有人可以帮忙吗?我不知道我错过了什么!

谢谢!

2 个答案:

答案 0 :(得分:1)

您的示例应该有效,请检查控制台中的任何错误。这是一个有效的例子:

var app = angular.module('myApp', ['ngSanitize', 'ui.bootstrap']);
app.controller('myCtrl', function($scope, $sce) {
  $scope.alerts = [];
  $scope.addAlert = function(type, msg) {
    $scope.alerts.push({
      "type": type,
      "msg": msg
    });
  }
  $scope.addAlert('danger', $sce.trustAsHtml('Invalid Alias Name: Certain limitations apply to alias naming. <a href="http://google.com/">Please refer  to the documentation</a>'));
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.6.9/angular-sanitize.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

<div ng-app="myApp" ng-controller="myCtrl">

  <div uib-alert ng-repeat="alert in alerts" ng-class="'alert alert-{{alert.type}}'">
    <span ng-bind-html="alert.msg"></span>
  </div>

</div>

注意:

  • 注入ngSanitize模块
  • 注入$sce
  • 使用<div uib-alert代替<uib-alert可选
  • 使用正确的bootstrap CSS语法将type更改为ng-class

答案 1 :(得分:0)

您可以尝试类似下面的代码,也可以针对给定的示例方案检查此工作plunker

<强>模板:

<body ng-controller="MainCtrl">
    <div ng-repeat="alert in alerts">
      <h4 ng-bind="alert.title"></h4>
      <span ng-bind-html="alert.msg | formatContent"></span>
    </div>
</body>

<强>控制器:

app.controller('MainCtrl', function($scope, $sce) {
  $scope.alerts=[];
  $scope.addAlert=function(title, msg){
    $scope.alerts.push({title: title, msg: msg});
  }
  $scope.addAlert('danger', 'Invalid Alias Name: Certain limitations apply to alias naming. <a href="http://google.com/">Please referto the documentation</a>');
});

app.filter('formatContent', ['$sce', function($sce){
  return function(input){
    return $sce.trustAsHtml(input);
  }
}]);

我已经使用过滤器更新了我的答案以实现它,如上面的代码所示,还要检查this plunker link是否正在使用过滤器实现。