javascript - ng-bind 工作正常,为什么 ng-bind-html 不工作

标签 javascript angularjs

   angular.module('form', []).controller('formcontroller', ['$scope',
      function($scope) {
        $scope.input;
        $scope.hello = "<h1> Welcome</h1>";
      }
    ]);
<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>

我试过用

它导致输出为

<h1> Welcome</h1>

我尝试通过替换 ng-bind-html 不唤醒并抛出错误。

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

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

Error: $sce:unsafe Require a safe/trusted value Attempting to use an unsafe value in a safe context.

请解释。

最佳答案

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

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

miAp.controller('demoController', function($scope) {
     $scope.bar = "<h1> Welcome</h1>";
  });
<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>

关于javascript - ng-bind 工作正常,为什么 ng-bind-html 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40929941/

相关文章:

javascript - 链接函数没有被调用

javascript - 工厂返回返回函数,而不是函数的产物

javascript - AngularJS 中的固定头表

javascript - 如何孤立地测试纯函数调用树?

javascript - 如何在 Cytoscape JS 中设置节点的位置

javascript - 我收到错误。 Angular .js :13550 TypeError: Cannot read property '$invalid' of undefined

angularjs - 使用但不公开 API (AngularJs/NodeJs)

javascript - AngularJS $http 以及如何获取错误响应

javascript - 多次使用 jQuery $() 运算符是否会对性能产生影响?

javascript - 如何在 ng-repeat 中设置作用域变量?