Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS limitTo using HTML tags

Tags:

angularjs

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

like image 604
Sericaia Avatar asked Nov 21 '14 15:11

Sericaia


3 Answers

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.

like image 114
Sericaia Avatar answered Nov 17 '22 21:11

Sericaia


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/

like image 41
Caçapava Avatar answered Nov 17 '22 22:11

Caçapava


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/

like image 1
ACOMIT001 Avatar answered Nov 17 '22 20:11

ACOMIT001