0

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);
            });
        }
    };

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

I can't have the <a ui-sref="{{item.state}}"></a> on html fixed because all the panels of dashboard are dynamic and not necessary there are elements like <a>, look my html in my post updated
@DiogoSoares did you try the other suggest option, ng-bind-compile..that should work..
I used the ng-bind-compile and is working but launched an exception "Uncaught Error: [$rootScope:infdig]" it is doing looping infinity of my elements
I got now and I posted the solution
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.