How to limit character number in ng-bind-html in AngularJS?

How to limit the number of characters for a ng-bind-html result in angularJS? Is it possible?

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

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

+6
source share
4 answers

You can use 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++){ console.log(data[i].Src) // $filter('limitTo')(input, limit) 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.

+4
source

AngularJS Restriction Using HTML Tags

@Sericaia got a great answer

She creates her own filter as follows:

 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 uses it in the view:

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

You might need to do some CSS tricks in the model view in html. For example, if you have long text, you can limit the number of lines, as here Limit text length to n lines using CSS

0
source

To add "read more" or "..." at the end of the truncated text, I added a little tweak to the @Yeysides answer , expanding @Sericaia "AngularJS restriction 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 uses it in the view:

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

Source: https://habr.com/ru/post/978890/


All Articles