0

I came across this post, which entails more or less exactly what I want to do: AngularJS - Is it possible to use ng-repeat to render HTML values?

As of right now, the code looks like this, rendering correctly as text:

<div ng-repeat="item in items.Items">
        {{item}}<br>
</div>

I want this to render as HTML now, so taking from that post, I have it looking something like this:

<div ng-repeat="item in items.Items" ng-bind-html-unsafe="item">
    <br>
</div>

However, nothing renders as a result. Does anyone know why that is? I have also tried setting ng-bind-html-unsafe to "{{item}}", which had no effect

4
  • Use ng-bind-html ... also out of curiosity what are you accomplishing with the 'br'? The ng-repeat suggests you are repeating the 'div', a div by default is display block, which would stack the elements the same way you would achieve with a breaking line Commented Mar 14, 2016 at 17:48
  • 1
    Have you brought in the $sanitize module? stackoverflow.com/questions/19415394/… Commented Mar 14, 2016 at 17:48
  • Can you provide a fiddle ? What does Items consist of ? Commented Mar 14, 2016 at 17:49
  • stackoverflow.com/questions/19415394/… Commented Mar 14, 2016 at 17:49

2 Answers 2

1

You should use ng-bind-html, and you could do that:

 $scope.myHTML = $sce.trustAsHtml('<b>some</b> html');

See the updated fiddle.

In your case use some function or pass the array in the controller first:

$scope.getHtml = function(v){
   return $sce.trustAsHtml(v);
};
Sign up to request clarification or add additional context in comments.

Comments

0

It is always a good practice to mark the html that one is binding from the .js file to the .html which are in string format, as safe.

One way, it can be achieved is by making use of AngularJS's dependency injection with $sce. One can read more about it, in length here.

I have created a demo using a list, since you have shared only the HTML but not the JS, so I have assumed one and illustrated how to make use of it by trusting the HTML string using $sce.trustAsHtml().

Refer demo.

Please have a look at the code below:

HTML:

<div ng-app="app" ng-controller="test">
  <div ng-repeat="item in items" ng-bind-html="item">
  </div>
</div>

JS:

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

app.controller('test', function($scope, $sce) {
  $scope.data = [{
    "Items": [{
      "data": "<p>Item 1</p>"
    }, {
      "data": "<p>Item 2</p>"
    }, {
      "data": "<p>Item 3</p>"
    }, {
      "data": "<p>Item 4</p>"
    }]
  }];
  $scope.items = [];
  angular.forEach($scope.data[0].Items, function(v, k) {
    $scope.items.push($sce.trustAsHtml(v.data));
  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.