ng-bind工作正常,为什么ng-bind-html无效

时间:2016-12-02 10:26:19

标签: javascript angularjs



   angular.module('form', []).controller('formcontroller', ['$scope',
      function($scope) {
        $scope.input;
        $scope.hello = "<h1> Welcome</h1>";
      }
    ]);
&#13;
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

</head>

<body>
  <form ng-app="form" ng-controller="formcontroller">
    <span ng-bind="hello"></span>
    
    <span ng-bind-html="hello"></span>
  </form>
 
</body>

</html>
&#13;
&#13;
&#13;

我尝试使用

       

导致输出为

<h1> Welcome</h1>

我尝试通过替换ng-bind-html而不是woking并抛出错误。

<script>
      angular.module('form', []).controller('formcontroller', ['$scope', function($scope) {

               $scope.hello="<h1> Welcome</h1>";
    }]);
    </script>
     

错误:$ sce:unsafe需要安全/可信值尝试使用   安全环境中的不安全价值。

请解释。

4 个答案:

答案 0 :(得分:3)

如果包含angular-sanitize脚本,则通过将HTML解析为标记来清理输入

&#13;
&#13;
var miAp = angular.module('miAp', ['ngSanitize']);

miAp.controller('demoController', function($scope) {
     $scope.bar = "<h1> Welcome</h1>";
  });
&#13;
<html>

<head>
  <meta charset="utf-8">
  <title>ngBind</title>
  
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular-sanitize.min.js" type="text/javascript"></script>
  
  <script src="cookies.js"></script>
</head>

<body ng-app="miAp" ng-controller="demoController">
   <div ng-bind-html="bar"></div>
</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以安装并添加ngSanitize

这应该可以解决错误。

答案 2 :(得分:0)

使用ng-bind-html绑定html字符串时,需要将该html标记为安全,以防止出现XSS和其他安全问题。这是由Angular的默认情况下启用的Strict Contextual Escaping(SCE)模式检查的。

您可以在此链接中看到更多内容:https://docs.angularjs.org/error/ $ sce / unsafe。

要解决此问题,您可以查看此问题: With ng-bind-html-unsafe removed, how do I inject HTML?

希望这有帮助!感谢

答案 3 :(得分:-2)

试试这个

<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular-sanitize.min.js" type="text/javascript"></script>

var App = angular.module('sanitize', ['ngSanitize']);

App.controller('demoController', function($scope) {
     $scope.bar = "<h1> Welcome</h1>";
  });

<h1 data-ng-bind="hello"></h1>