AngularJS 在双花括号表示法中呈现 HTML [英] AngularJS render HTML within double curly brace notation

查看:35
本文介绍了AngularJS 在双花括号表示法中呈现 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包含 HTML 的 JSON 变量.

通过这样做:{{source.HTML}} Angular 显示 &lt;&gt; 而不是 <>.

我该怎么做才能让 Angular 呈现实际的 HTML?



更新:
这是我的控制器:

app.controller('objectCtrl', ['$scope', '$http', '$routeParams',功能($scope,$http,$routeParams){var productId = ($routeParams.productId || "");$http.get(templateSource+'/object?i='+productId).then(函数(结果){$scope.elsevierObject = {};angular.extend($scope,result.data[0]);});}]);

在我的 HTML 中,我可以使用:

{{foo.bar.theHTML}}

解决方案

是否要显示 HTML(如<b>Hello</b>)或渲染 HTML(如Hello)?

  • 要显示的话,大括号就够了.但是,如果您拥有的 html 具有 html 实体(如 &lt;stuff),您需要手动取消转义它,请参阅 这个问题.

  • 如果你想渲染它,你需要使用 ng-bind-html 指令而不是花括号(仅供参考,它是 ng-绑定 指令).您需要使用 $sce.trustAsHtml 告诉 Angular 注入该指令的内容是安全的.

请参阅以下两种情况的示例:

angular.module('test', []).controller('ctrl', function($scope, $sce) {$scope.HTML = '<b>你好</b>';$scope.trust = $sce.trustAsHtml;});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><div ng-app="test" ng-controller="ctrl"><div>显示:{{HTML}}</div><div>渲染:<span ng-bind-html="trust(HTML)"></span></div>

I have JSON variables that contain HTML.

By doing: {{source.HTML}} Angular is showing &lt; and &gt; instead of < and >.

What can I do to have Angular render the actual HTML?



UPDATE:
This is my controller:

app.controller('objectCtrl', ['$scope', '$http', '$routeParams',
  function($scope, $http, $routeParams) {

    var productId = ($routeParams.productId || "");

    $http.get(templateSource+'/object?i='+productId)
       .then(function(result) {
          $scope.elsevierObject = {};
          angular.extend($scope,result.data[0]);
        });
  }]);

Inside my HTML i can then use:

<div>{{foo.bar.theHTML}}</div>

解决方案

Do you want to show the HTML (like <b>Hello</b>) or render the HTML (like Hello) ?

  • If you want to show it, the curly bracket is enough. However if the html you have has html entities (like &lt;stuff) you need to manually unescape it, see this SO question.

  • If you want to render it, you need to use the ng-bind-html directive instead of curcly bracket (which, FYI, is a shortcut to the ng-bind directive). You need to tell Angular that the content injected into that directive is safe, using $sce.trustAsHtml.

See example of both cases below:

angular.module('test', []).controller('ctrl', function($scope, $sce) {
  $scope.HTML = '<b>Hello</b>';
  
  $scope.trust = $sce.trustAsHtml;
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="ctrl">
  <div>Show: {{HTML}}</div>
  <div>Render: <span ng-bind-html="trust(HTML)"></span></div>
</div>

这篇关于AngularJS 在双花括号表示法中呈现 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆