w1n78
w1n78

Reputation: 789

parse html within ng-repeat

I've been searching for hours now and I can't seem to find how to parse HTML code when retrieving using ng-repeat. I checked out $sce.trustAsHtml but I don't know how to apply it in my code.

html file:

<div ng-app="myApp">
<div ng-controller="MyCtrl">
    <h2>My Links</h2>
    <table class="table table-bordered">
        <thead>
            <tr>
                <td>Name</td>
                <td>URL</td>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="stuff in myStuff()">
                <td>{{stuff.name}}</td>
                <td>{{stuff.url}}</td>
            </tr>
        </tbody>
    </table>
</div>

javascript

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

myApp.controller('MyCtrl', function ($scope) {
$scope.myStuff = function() {
    return [
        {
            'name':'Google',
            'url':'<a href="http://google.com">Google</a>'
        },
        {
            'name':'Yahoo',
            'url':'<a href="http://yahoo.com">Yahoo</a>'
        },
        {
            'name':'Microsoft',
            'url':'<a href="http://microsoft.com">Microsoft</a>'
        }
    ];
};
});

It's displaying the HTML source but I want it compile the code. Is my JS approach wrong? I'll be applying it to a json file using $http directive once I figure this out. Can anyone shed some light? I have my code at http://jsfiddle.net/s2ykvy8n/

Thanks.

Upvotes: 2

Views: 1189

Answers (2)

PSL
PSL

Reputation: 123739

Include ng-sanitize script and in your module add dependency.

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

and just use ng-bind-html

     <td ng-bind-html="stuff.url"></td>

and you are good to go:-

Plnkr

With what you are doing, the html in the binding will be displayed as textcontent in the element while processed by interpolation directive.

Upvotes: 5

dannypaz
dannypaz

Reputation: 1294

My first inclination (since from your example, you are just returning links) is to advise you to remove the html from your returned json and just return the url as a string.

Format:

{
    'name': 'Google',
    'url': 'http://google.com'
}

Then your HTML looks like this,

<tbody>
    <tr ng-repeat="stuff in myStuff()">
        <td>{{stuff.name}}</td>
        <td><a href="{{stuff.url}}">{{stuff.name}}</a></td>
    </tr>
</tbody>

But, if you MUST have HTML strings in your json file, I would take a look at $compile. There are examples towards the bottom that can help you on how you can create a directive to compile your 'url' string to HTML

Upvotes: 1

Related Questions