mhartington
mhartington

Reputation: 7025

Using HTML tags in Angular Scope Data

In my Angular app, I have some data that I need to include html tags in and I'm having some trouble making sure it gets escaped.

 $scope.groups = [
    {
      'name': 'min',
      'item': '<h1>This is some awsome H1</h1><ul><li>yup></li></ul>',
    },
     {
      'name': 'min',
      'item': '<h1>This is some awsome H1</h1><ul><li>yup></li></ul>',
    },
     {
      'name': 'min',
      'item': '<h1>This is some awsome H1</h1><ul><li>yup></li></ul>',
    },
     {
      'name': 'min',
      'item': '<h1>This is some awsome H1</h1><ul><li>yup></li></ul>',
    }
  ];

And here's my html

<div ng-repeat="group in groups">
  <li>{{group.name}}</li>
  <li>{{group.item}}</li>
</div>

I tried just including some of angular's ng-sanitize, but I've only seen examples where its a single object, and not an array.

See here

I try to add ng-bind-html="groups" to the main div but my data comes out as [object Object].

Any ideas? Any help is appreciated!

Upvotes: 1

Views: 1434

Answers (2)

mingos
mingos

Reputation: 24502

The ngBindHtml directive accepts a string containing HTML and should be used directly on the tag wherein that HTML string should be rendered. Instead of using it on the container, use it directly on the second <li> like this:

<div ng-repeat="group in groups">
    <li>{{group.name}}</li>
    <li ng-bind-html="group.item"></li>
</div>

@javaCoin created a Plunker illustrating this; let's not let it go to waste and paste it here: http://plnkr.co/edit/PFaxHqpyQvWqln5ABHRc?p=preview

Upvotes: 4

Casao
Casao

Reputation: 542

ng-bind-html is on the specific item you want the code in.

So, your example becomes:

<div ng-repeat="group in groups">
  <li>{{group.name}}</li>
  <li ng-bind-html="group.item"></li>
</div>

http://plnkr.co/edit/CO5WUCgBnOEJrVoKKrEE?p=preview shows a quick and dirty example of this.

Upvotes: 1

Related Questions