how to limit character number in ng-bind-html in AngularJS?
Asked Answered
P

4

6

How can I limit number of characters for ng-bind-html result in angularJS? Is it possible?

For example there is <span>some text </span> in js file and with $sce and ng-bind-html transform to html.

I want to show som... How can I limit it?

Pentobarbital answered 30/11, 2014 at 8:38 Comment(1)
This is yours answer!!! pretty nice!!Anosmia
C
4

You can use the limiTo filter in your controller - limitTo fliter.

Controller:

app.controller('myCtrl', ['$scope','$sce','$filter',
function($scope, $sce, $filter) {
    var dataObj = [];        
    for(var i = 0; i < data.length; i++){

        var content = $filter('limitTo')(data[i].Content, 150)
        var itemObj = {
            Content: $sce.trustAsHtml(content)
        }
        dataObj.push(itemObj);
    }
    $scope.ngRepeatArray = dataObj;  
}])

HTML

<ul>
    <li ng-repeat="item in ngRepeatArray">
          <p ng-bind-html="item.Content"></p>
    </li>
</ul>

Hope this helps.

Cut answered 7/12, 2014 at 22:56 Comment(0)
H
4

AngularJS limitTo using HTML tags

@Sericaia had a great answer

She creates a custom filter like so:

angular.module('limitHtml', [])
    .filter('limitHtml', function() {
        return function(text, limit) {

            var changedString = String(text).replace(/<[^>]+>/gm, '');
            var length = changedString.length;

            return length > limit ? changedString.substr(0, limit - 1) : changedString;
        }
    });

And then utilizes it in the view:

<span ng-bind-html="text | limitHtml: maxNumberOfChar"></span>
Headword answered 23/9, 2015 at 14:56 Comment(0)
B
0

Maybe you need to do some CSS tricks on your model represenation in html. For example if you have long text you can limit number of lines like here Limit text length to n lines using CSS

Blubberhead answered 1/12, 2014 at 8:25 Comment(0)
C
0

To add a "read more" or "..." at the end of the truncated text, I added a small tweak to @Yeysides's answer extending @Sericaia's "AngularJS limitTo using HTML tags".

Use a variable with the suffix string, then call it.

angular.module('limitHtml', [])
    .filter('limitHtml', function() {
        return function(text, limit) {

            var changedString = String(text).replace(/<[^>]+>/gm, '');
            var length = changedString.length;
            var suffix = ' ...';

            return length > limit ? changedString.substr(0, limit - 1) + suffix : changedString;
        }
    });

And then utilizes it in the view:

<span ng-bind-html="text | limitHtml: maxNumberOfChar"></span>
Chilt answered 6/7, 2016 at 1:1 Comment(2)
This works for AngularJS, not Angular 2. I have it tested and deployed. Have you checked if the filter is being triggered correctly?Chilt
It works for me, but I did declare a variable for maxNumberOfChar in the controller scope. eg $scope.maxNumberOfChar = 100;Bobbysoxer

© 2022 - 2024 — McMap. All rights reserved.