пятница, 30 мая 2014 г.

Plain text AngularJS filter

Many times on different web projects there is an requirement to remove HTML tags from the text (that comes from some remote place and should be displayed on the web page). Here I will provide approach, how to do it through AngularJS filter. So, filter code itself:

/**
 * Filter removes HTML from given string value.
 */
angular.module("myApp").filter('plainText', function() {
  return function(val) {
    //remove html tags
    var s1 = val.replace(/<\/?[^>]+(>|$)/g, "");

    //translate special symbols
    var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
    var translate = {"nbsp": " ","amp" : "&","quot": "\"","lt"  : "<","gt"  : ">"};
    return ( s1.replace(translate_re, function(match, entity) {
      return translate[entity];
    }) );
  };
});

And how it is being used on HTML page;
{{htmlMessage.body | plainText}}

Комментариев нет:

Отправить комментарий