在ng-repeat中打印HTML

时间:2018-07-23 15:28:23

标签: html angularjs

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

a:b:c:d

然后在我的HTML中循环浏览这些内容以显示它们:

$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"
        }
    ];

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

我通过更改

尝试了http://guides.rubyonrails.org/i18n.html#using-safe-html-translations的建议
<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>

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

但这只是用来停止任何打印。任何人都可以提供其他建议或修复吗?


请注意:我只是从angularjs和Web开发开始,所以请尽量保持您的回答简单,如果需要澄清,请与我同在。

1 个答案:

答案 0 :(得分:1)

您可以使用ngSanitize并使您的answer拥有这样的html:

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

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

然后像这样绑定它们:<p ng-bind-html="faq.answer"></p>

请参见下面的有效完整示例:

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>