AngularJS limitTo using HTML tags
Asked Answered
K

4

9

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

Kickoff answered 21/11, 2014 at 15:5 Comment(0)
K
15

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.

Kickoff answered 24/11, 2014 at 11:7 Comment(1)
Although the main idea to limitHtml filter worked for me but I had to further $sce.trustAsHtml(val) to make it work. Thank youSuperb
M
2

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/

Meridel answered 21/11, 2014 at 16:0 Comment(0)
D
1

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/

Drews answered 21/11, 2014 at 15:22 Comment(0)
L
0

Why not displaying it based on a filter length?

Just add a limitTo filter

{{ text| limitTo:maxNumberOfChar }}
Laveralavergne answered 21/11, 2014 at 15:8 Comment(2)
As I said in the question, your solutions just works when you don't have HTML tags inside your textKickoff
Ah, sorry, I misunderstood. Probl you want first to remove the text between tags. #20956270Laveralavergne

© 2022 - 2024 — McMap. All rights reserved.