【问题标题】:Using HTML Entities within AngularJS strings在 AngularJS 字符串中使用 HTML 实体
【发布时间】:2014-02-20 21:02:52
【问题描述】:

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

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>

【问题讨论】:

标签: javascript string angularjs


【解决方案1】:

不需要需要$sce 来绑定到带有html 的字符串。您只需将ngSanitize 注入您的应用程序(它不是核心模块),然后使用ng-bind-html 属性指令。

JavaScript

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

app.controller('MainCtrl', function($scope) {
    $scope.title = '&#189; Cookies &amp; <span class="cream">Cream</span>';
});

HTML

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

Plunkr

【讨论】:

    【解决方案2】:

    $sce。您需要明确告诉 Angular 内容是 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

    【讨论】:

    • 他必须使用ng-bind-html
    • 为了让 ng-bind-html 工作,你也需要 angular-sanitize
    猜你喜欢
    • 2022-01-05
    • 2023-03-11
    • 1970-01-01
    • 2020-04-15
    • 2011-05-12
    • 2011-03-03
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    相关资源
    最近更新 更多