Diogo Soares
Diogo Soares

Reputation: 55

Convert text to elements of angularjs

I have a dashboard dynamic and there is a json that I fill with elements html in format text, for example:

var items = [
 {"id": "panel1", "description": "<div><a ui-sref='page1'>link a</a></div>"},
 {"id": "panel2", "description": "<div><a ui-sref='page2'>link b</a></div>"}
];
vm.items = items;

but when I do the ng-repeat on html it isn't turning the attribute in angular element, How I do to work this?

This is my html

<li class="dashboard-panel" data-ng-repeat="item in dashboardCtrl.items" data-ng-class="item.id == 'novo' ? 'background-new-panel' : ''">
   <div class="content" id="{{item.id}}" data-ng-bind-html="item.descricao | trustAsHtml" style="display: block;"></div>
</li>

Code of solution:

return {
        restrict: 'A',
        replace: true,
        link: function (scope, element, attrs) {
            scope.$watch(attrs.ngHtmlCompile, function (html) {
                element[0].innerHTML = html;
                $compile(element.contents())(scope);
            });
        }
    };

Upvotes: 0

Views: 74

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

In your case you could have use ng-bind-html, but that would not help you to compile your directives of html for security reasons. It will just put html on DOM. Rather I'd suggest you to granular your json response, by separating description and state, so that would be easier to render on UI.

var items = [
 {"id": "panel1", "description": "link a", state: 'page1'},
 {"id": "panel2", "description": "link b", state: 'page1'}
]; 
$scope.items = items;

HTML

<div ng-repeat="item in items">
    <a ui-sref="{{item.state}}">{{item.description}}</a>
</div>

Otherwise you could achieve the same by using ng-bind-compile directive

Upvotes: 2

Ben
Ben

Reputation: 2706

AngularJS has built-in XSS protection which means that interpolated data is interpreted as a string and not as HTML.

If you want to interpolate an HTML string, you need to use AngularJS' $sce library to declare that you want trust the HTML string to actually be safe.

Upvotes: 1

Related Questions