Sericaia
Sericaia

Reputation: 450

AngularJS limitTo using HTML tags

I have some bindings in AngularJS and I want to limit the length of characters displayed. It's a quite simple question when you have just a simple text content.

However, I have text that contains HTML tags:

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

and also

$scope.maxNumberOfChar = 10;

When I use the following line it counts the number of chars taking into account HTML tags.

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

Thanks in advance

Upvotes: 9

Views: 5653

Answers (4)

Sericaia
Sericaia

Reputation: 450

I've created a solution, using a 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 the correspondent usage, similar to limitTo filter

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

Note that, in this case I am also using an html-binding, specific of my solution.

Upvotes: 15

Alberto Silva
Alberto Silva

Reputation: 21

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/

Upvotes: 2

ACOMIT001
ACOMIT001

Reputation: 510

To count only the number of non HTML chars, 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);

I've included a further example here: http://jsfiddle.net/n3qjm2u5/

Upvotes: 1

Mario Levrero
Mario Levrero

Reputation: 3367

Why not displaying it based on a filter length?

Just add a limitTo filter

{{ text| limitTo:maxNumberOfChar }}

Upvotes: 0

Related Questions