【问题标题】:How to show html in angularjs template instead of string?如何在 angularjs 模板中显示 html 而不是字符串?
【发布时间】:2014-07-07 23:42:05
【问题描述】:

我的作用域中有一个变量:

$scope.myvar = "Hello<br><br>World"

在我的模板中我使用:

<div>{{myvar}}</div>

问题是 myvar 显示文字文本,而我希望它显示换行符。这个怎么做?请注意,我想让它这样,如果我将来用其他 HTML 更新 myvar,那么页面上显示的应该是“编译”的 html,而不是其中包含 html 标签的文字字符串。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    您可以为此使用 ngBindHtml
    请记住,由于 Angular 的 Strict Conceptual Escaping,需要对内容进行清理(使用附加模块 ngSanitize)或明确“trustedAsHtml”(使用 $sce.trustAsHtml())。后者应该只用于您知道安全的内容(例如,没有用户定义的内容)并且无论如何都不推荐使用。

    注意: ngSanitize 是非核心模块,应单独包含:
    &lt;script src=".../angular.min.js"&gt;&lt;/script&gt;
    &lt;script src=".../angular-sanitize.min.js"&gt;&lt;/script&gt;

    例子:

    /* Using ngSanitize */
    angular.module('app', ['ngSanitize'])
    .controller('myCtrl', function ($scope) {
        $scope.myHtml = 'Hello<br /><br />world !';
    });
    
    /* Using $sce.trustAsHtml() */
    angular.module('app', [])
    .controller('myCtrl', function ($sce, $scope) {
        $scope.myHtml = $sce.trustAsHtml('Hello<br /><br />world !');
    });
    

    请注意,ngSanitize 将过滤“不适当”的内容,而 $sce.trustAsHtml 将允许任何内容。

    另请参阅此short demo

    【讨论】:

      【解决方案2】:

      &lt;div&gt; 中使用ng-bind-html。示例如下:

      在您的html 文件中:

      <div ng-controller="ngBindHtmlCtrl">
          <div ng-bind-html="myvar"></div>
      </div>
      

      在你的js

      angular.module('ngBindHtmlExample', ['ngSanitize']) 
      
      .controller('ngBindHtmlCtrl', ['$scope', function ngBindHtmlCtrl($scope) {
         $scope.myvar = 'Hello<br><br>World';
                       }]);
      

      示例取自AngularJs doc。

      【讨论】:

        【解决方案3】:

        您可以使用ng-bind-html 直接绑定到 HTML。 Here's官方文档

        【讨论】:

          【解决方案4】:

          @ExpertSystem 是正确的,或者如果你像我一样懒惰,你可以这样做:

          lrApp.directive('bindHtml', function () {
          return {
              restrict: 'A',
              link: function (scope, elem, attrs) {
                  scope.$watch(attrs.bindHtml,function(nv,ov){
                      elem.html(nv);
                  });
              }
          };
          });
          

          【讨论】:

            【解决方案5】:

            1) 添加 angular-sanitize.js 库。此功能曾经是主库的一部分,但 Angular 团队一直在拆分部分以使其更加模块化。

            2) 使用 ng-bind-html 标签:

            <p ng-bind-html="myvar">
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2012-01-11
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-01-13
              • 2019-11-04
              • 1970-01-01
              • 2016-09-06
              相关资源
              最近更新 更多