{{foo.something.replace("\n","<br>")}}

30,090 views
Skip to first unread message

Paul Hammant

unread,
Feb 9, 2011, 8:43:13 AM2/9/11
to ang...@googlegroups.com
I can't do JS things in the middle of an Angular expression of course.  Like changing newlines from a JSON feed into the HTML equiv (as in the subj line)

What can I do instead?  I looked online for examples ( http://www.angularjs.org/Ng:format and alike ) but could not find what I was looking for.

Great work guys, by the way.

- Paul

Misko Hevery

unread,
Feb 9, 2011, 10:05:59 AM2/9/11
to ang...@googlegroups.com
Hi Paul,

you should be able to execute  {{foo.something.replace("\n","<br>") }} but RegExps are not allowed so '\n' is not the same as /\n/. In any case what you want is a filter which converts new lines to <br/>. Here is what I would do

register a new filter

angular.filter('newlines', function(text){
  return text.replace(/\n/g, '<br/>');
});

and then in the HTML I wold write

{{ foo.something | newline }} but that would still not do what you want since you want is to take the HTML as literal, so we need one more filter which is built in.

{{ foo.something | newline | html }}

The cool thing is that HTML filter is sanitizing, so it will be safe from malicious content.

Enjoy...

-- Misko


--
You received this message because you are subscribed to the Google Groups "Angular" group.
To post to this group, send email to ang...@googlegroups.com.
To unsubscribe from this group, send email to angular+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/angular?hl=en.

Paul Hammant

unread,
Feb 9, 2011, 12:26:41 PM2/9/11
to ang...@googlegroups.com
works perfectly.  which wiki page should i update ?

Misko Hevery

unread,
Feb 9, 2011, 1:45:42 PM2/9/11
to ang...@googlegroups.com
no more wiki. http://docs.angularjs.org/#!angular.filter.html but we are working on making docs better.

-- Misko
Message has been deleted

Exceldon Gumera

unread,
Jul 9, 2014, 1:55:45 AM7/9/14
to ang...@googlegroups.com, pa...@hammant.org
Hi Paul, 

I think I got it working now. haha. really sorry for the nuisance. 

I used ng-bind-html. :)

Thanks.

Don

Maruthi Prasad

unread,
Apr 5, 2016, 12:47:08 PM4/5/16
to AngularJS, pa...@hammant.org

This looks fine.But should we need to  write filter to handle all such scenario's,  html text containing \t \n \r etc ... to interpret them .
Reply all
Reply to author
Forward
0 new messages