我不想转义HTML标记,也不想在Angular应用程序中使用对象文字

I want not to escape HTML tags and to use object literal in Angular app

本文关键字:应用程序 文字 对象 Angular HTML 转义 标记 不想 我不想      更新时间:2023-09-26

我是AngularJS的新手。我不想转义HTML标记,并编写了下面的代码。

起初,在定义deliberatelyTrustDangerousSnipet()时,我成功地逃脱了HTML标记(在这个网站上有很好的顾问)。

其次,我想使用<div ng-bind-html="phone.snippet"></div>

<script>
  angular.module('plunker', ['ngSanitize'])
  .controller('MainCtrl', ['$scope', '$sce', function($scope, $sce) { 
    $scope.phone = 
      {'name': 'Nexus S',
       'snippet': '<iframe width="560" height="315" src="//www.youtube.com/embed/-RRqZ7FAlG0?rel=0" frameborder="0" allowfullscreen></iframe>'};
    // This works well
    $scope.deliberatelyTrustDangerousSnippet = function() {
      return $sce.trustAsHtml('<iframe width="560" height="315" src="//www.youtube.com/embed/-RRqZ7FAlG0?rel=0" frameborder="0" allowfullscreen></iframe>');
    };
    // This doesn't work
    //$sce.trustAsHtml($scope.article.content);
  }])
</script>
<div ng-controller="MainCtrl">
  <div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div>
  <!-- ### Can we write like below? ### -->
  <div ng-bind-html="phone.snippet"></div>
</div>    

代码也在Plunker上。

<!DOCTYPE html>
<html ng-app="plunker">
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular-sanitize.js"></script>
  </head>
  <body>
    <script>
      angular.module('plunker', ['ngSanitize'])
      .controller('MainCtrl', ['$scope', '$sce', function($scope, $sce) { 
        $scope.phone = 
          {'name': 'Nexus S',
           'snippet': '<iframe width="560" height="315" src="//www.youtube.com/embed/-RRqZ7FAlG0?rel=0" frameborder="0" allowfullscreen></iframe>'};
        $scope.phone.snippet = $sce.trustAsHtml($scope.phone.snippet);
      }])
    </script>
    <div ng-controller="MainCtrl">
      <div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div>
      <!-- ### Can we write like below? ### -->
      <div ng-bind-html="phone.snippet"></div>
    </div>    
  </body>
</html>

另一个选项是添加ngSanitize.js,这样就不需要执行$sce.trustAsHtml

您可以定义一个secureHtml过滤器。该过滤器会将您的表达式信任为类似的HTML

youApp.filter('secureHtml', function ($sce) {
    return function (input) {
      return $sce.trustAsHtml(input);
    }
  })

然后你可以在你的模板中使用过滤器,如下所示:

<div ng-bind-html="harmlessSnippet | secureHtml"></div>

与你的例子一起工作:http://plnkr.co/edit/IsW7Q6s4bySp8Eim40kf?p=preview