AngularJS Restriction Using HTML Tags

I have bindings in AngularJS and I want to limit the length of the characters displayed. This is a pretty simple question when you just have plain text content.

However, I have text containing HTML tags:

$scope.text = "<span><h1>Example</h1><p>Special Text</p></span>" 

and

 $scope.maxNumberOfChar = 10; 

When I use the following line, it counts the number of characters considering HTML tags.

What could be the best solution to solve this problem and count only the number of characters, discarding HTML tags?

Thanks in advance

+7
angularjs
source share
4 answers

I created a solution using simple filter and regex operations.

 var appFilters = angular.module('myApp.filters', []) .filter('limitHtml', function() { return function(text, limit) { var changedString = String(text).replace(/<[^>]+>/gm, ''); var length = changedString.length; return changedString.length > limit ? changedString.substr(0, limit - 1) : changedString; } }) 

and appropriate use, like limitTo filter

 <span ng-bind-html="text | limitHtml: maxNumberOfChar"></span> 

Please note that in this case I also use the html binding specific to my solution.

+15
source share

To count only the number of non-HTML characters, use something similar to the answer to this question: angularjs to output plain text instead of html

For example:

 var text = "<span><h1>Example</h1><p>Special Text</p></span>"; var length = String(text).replace(/<[^>]+>/gm, '').length; alert(length); 

Here I gave another example: http://jsfiddle.net/n3qjm2u5/

+1
source share

I created a filter, the logic is not so good, but it works

  <span ng-bind-html="text | limitHtml:maxNumberOfChar"></span> 

jsfiddle.net/4x6z283a/1/

+1
source share

Why not display it based on the length of the filter?

Just add a limitTo filter

 {{ text| limitTo:maxNumberOfChar }} 
0
source share

All Articles