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?
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?
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.
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>
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
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>
maxNumberOfChar
in the controller scope. eg $scope.maxNumberOfChar = 100;
–
Bobbysoxer © 2022 - 2024 — McMap. All rights reserved.