在 Angular 字符串中使用 HTML 实体 [英] Using HTML Entities within Angular strings

查看:24
本文介绍了在 Angular 字符串中使用 HTML 实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定我的 $scope 模型中包含 HTML 实体的字符串,我如何确保该实体正确显示为 HTML 字符而不是文字字符串?

HTML 实体 - MDN 词汇表

http://plnkr.co/edit/0BliljcDkj0vvj3jdEqz?p=preview

<头><script data-require="angular.js@*"数据-semver="1.2.13"src="http://code.angularjs.org/1.2.13/angular.js"></script><身体><div ng-controller="htmlChar">{{title}}</div><脚本>angular.element(document).ready(function(){var app=angular.module("app",[]);app.controller("htmlChar",function($scope){$scope.title = "&copy; Acme";});angular.bootstrap(document, ['app']);});</html>

解决方案

使用 $sce.您需要明确地告诉 angular 内容是 html.

<脚本>angular.element(document).ready(function(){var app=angular.module("app",[]);app.controller("htmlChar",function($scope, $sce){$scope.title = $sce.trustAsHtml("&copy; Acme");});angular.bootstrap(document, ['app']);});

http://plnkr.co/edit/9iNnRC7AxFptnQZLPtYR?p=preview

Given a string in my $scope model which contains an HTML entity, how do I ensure that the entity is properly displayed as an HTML character rather than a literal string?

HTML entity - MDN Glossary

http://plnkr.co/edit/0BliljcDkj0vvj3jdEqz?p=preview

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@*" 
            data-semver="1.2.13" 
            src="http://code.angularjs.org/1.2.13/angular.js"></script>

  </head>

  <body>
    <div ng-controller="htmlChar">{{title}}</div>

    <script>

      angular.element(document).ready(function(){

        var app=angular.module("app",[]);
        app.controller("htmlChar",function($scope){
          $scope.title = "&copy; Acme";
        });
        angular.bootstrap(document, ['app']);

      });

    </script>

  </body>
</html>

解决方案

With $sce. You need to explicitely tell angular the content is html.

<div ng-controller="htmlChar" ng-bind-html="title"></div>

<script>

  angular.element(document).ready(function(){

    var app=angular.module("app",[]);
    app.controller("htmlChar",function($scope, $sce){
      $scope.title = $sce.trustAsHtml("&copy; Acme");
    });
    angular.bootstrap(document, ['app']);

  });

</script>

http://plnkr.co/edit/9iNnRC7AxFptnQZLPtYR?p=preview

这篇关于在 Angular 字符串中使用 HTML 实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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