3

Is there any reason this is not working ? :

this.categoriesId = $rootScope.categoriesList.map(function(obj) {
  return obj.id;
}).join('<br />');
this.categoriesName = $rootScope.categoriesList.map(function(obj) {
  return obj.name;
}).join('<br />');

and in the view :

<b>Categories ID :</b><br/><br/>
{{h.categoriesId}}
<hr>
<b>Categories Name :</b><br/><br/>
{{h.categoriesName}}

There is no line breaks, the <br /> isn't interpreted.

How can I work around this ?

3
  • you mean that <br /> is displayed as text ? Commented Feb 22, 2016 at 14:00
  • 1
    I'll suggest you to use ng-repeat directive Commented Feb 22, 2016 at 14:02
  • Possible duplicate of AngularJS : Insert HTML into view Commented Feb 22, 2016 at 14:02

3 Answers 3

4

Because Angular escapes the HTML in your string before it inserts it into the DOM, in order to prevent XSS attacks.

Messy Fix

Use the ng-bind-html directive to insert the HTML as is.

<span ng-bind-html="h.categoriesName"></span>

Make sure to include the $sanitize service, and ng-bind-html will automatically sanitize your string to make sure it's safe within its context.

Clean Fix

Use ng-repeat to iterate over the list without needing to worry about inserting markup into your string.

<b>Categories Name :</b><br/><br/>
<span ng-repeat="name in categoriesList">
  {{name}}<br />
</span>
Sign up to request clarification or add additional context in comments.

6 Comments

$sce does sanitize ng-bind-html. You haven't accounted for that. Answer is misleading
@charlietfl Updated.
also can't use it without sanitize included as it will throw error and output nothing. So realistically Safe Fix is still misleading
Yep, got it: "Make sure to include the $sanitize service"
Got it working with a slight modification : <span ng-repeat="category in $root.categoriesList"> {{category.name}}<br /> </span>
|
1

{{}} is only interpreted as text , not html

Use ng-repeat , there is no need to parse array to html

Comments

0

Try this way:

<b>Categories Name :</b><br/><br/>
<span ng-bind-html="h.categoriesName"><span>

Or create map and join filter:

app
.filter('map', function () {
    return function (arr, prop) {
        return arr.map(function (item) {
            return item[prop];
        });
    };
})
.filter('join', function () {
    return function (arr, sep) {
        return arr.join(sep);
    };
});

HTML:

<span ng-bind-html="categoriesList | map: 'name' | join '<br/>'"><span>

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.