【问题标题】:Printing HTML in ng-repeat [duplicate]在 ng-repeat 中打印 HTML [重复]
【发布时间】:2018-12-31 02:50:43
【问题描述】:

我有一个 ngController,其中包含一系列问题和答案:

$scope.faqs = [
        {
            question: "QUESTION 1",
            answer: "ANSWER 1"
        },
        {
            question: "What is the dress code?",    
            answer: "See <a href=\"https://www.brides.com/story/wedding-dress-code-explained\">here</a>."
        },
        {
            question: "QUESTION 3",
            answer: "ANSWER 3"
        }
    ];

然后在我的 HTML 中循环显示它们:

<div> 
    <div ng-controller="FAQController" class="FAQ_container">
        <div ng-repeat="faq in faqs">
            <button class="collapsible">{{ faq.question }}</button>
            <div class="content">
                <p>{{ faq.answer }}</p>
            </div>
        </div>
    </div>
<div>

但是,对于我数组中的中间问题,它将整个项目打印为字符串。我可以理解为什么会这样,但是我希望它具有可点击的链接。

我已经尝试了How to parse HTML in ng-repeat in angular.js 的建议,方法是更改​​我的

<p>{{ faq.answer }}</p>

<p ng-bind-html-unsafe="faq.answer"></p>

但这只是停止了任何打印。任何人都可以提供替代建议或解决方法吗?


请注意:我刚开始使用 angularjs 和 web 开发,所以请尽量保持简单的回答,如果我需要澄清,请多多包涵。

【问题讨论】:

    标签: html angularjs


    【解决方案1】:

    您可以使用ngSanitize 并让您的answers 被信任具有这样的html:

    angular.forEach($scope.faqs, function(faq) {
      faq.answer = $sce.trustAsHtml(faq.answer);
    });
    

    为此,您需要使用$sce 服务。

    然后像这样绑定它们:&lt;p ng-bind-html="faq.answer"&gt;&lt;/p&gt;

    请参阅下面的工作完整示例:

    angular.module('app', ['ngSanitize']).controller('FAQController', function($scope, $sce) {
      $scope.faqs = [{
          question: "QUESTION 1",
          answer: "ANSWER 1"
        },
        {
          question: "What is the dress code?",
          answer: "See <a href=\"https://www.brides.com/story/wedding-dress-code-explained\">here</a>."
        },
        {
          question: "QUESTION 3",
          answer: "ANSWER 3"
        }
      ];
      angular.forEach($scope.faqs, function(faq) {
        faq.answer = $sce.trustAsHtml(faq.answer);
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.14/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.14/angular-sanitize.js"></script>
    
    <div ng-app="app">
      <div ng-controller="FAQController" class="FAQ_container">
        <div ng-repeat="faq in faqs">
          <button class="collapsible">{{ faq.question }}</button>
          <div class="content">
            <p ng-bind-html="faq.answer"></p>
          </div>
        </div>
      </div>
      <div>

    【讨论】:

    • 完美,谢谢。我已经读过一些关于这个但没有设法让它工作!
    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 2021-04-16
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    相关资源
    最近更新 更多