1

I have an ngController which contains, amongst other things, an array of questions and answers:

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

In my HTML I then cycle through these to display them:

<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>

However, for the middle question in my array, it prints the whole item as a string. I can understand why this is the case, however I would like for it to have the link clickable.

I have tried the suggestion from How to parse HTML in ng-repeat in angular.js by changing my

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

to

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

but that has just served to stop anything printing. Can anyone help with an alternative suggestion or fix please?


Please note: I am just starting out with angularjs and web development so please try to keep your answers simple and bear with me if I have to ask for clarification.

lioness99a
  • 327
  • 4
  • 19

1 Answers1

1

You could use ngSanitize and make your answers to be trusted has html like this:

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

For this you will need to use the $sce service.

And then bind them like this: <p ng-bind-html="faq.answer"></p>

See below working full sample:

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>
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80