Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to limit characters in ng-bind-html Angular JS

Tags:

angularjs

I am trying to limit the characters i see on my angular js app. Currently i am using:

<p ng-bind-html="item.get('Content') | limitTo: 150"></p>  

But no joy, any ideas...

like image 580
Sole Avatar asked Jul 15 '15 14:07

Sole


3 Answers

I don't think that will work with ng-bind-html. This is for binding actual html code to the page. ng-bind should work fine.

<p ng-bind="item.get('Content') | limitTo: 150"></p>  

See plunkr http://plnkr.co/edit/y0LXMMFi6sU9AhShvuha?p=preview

EDIT:

Since you do have HTML code in it, you'll need to use ngSanitize. You can read about that here: https://docs.angularjs.org/api/ngSanitize

Add the reference to angular-sanitize.js, then import it into the app

var app = angular.module('plunker', ['ngSanitize']);

Then your original code should work fine, although it's likely parts of it will be cut off, including ending tags, so you'll need to deal with that.

See plnkr: http://plnkr.co/edit/y0LXMMFi6sU9AhShvuha?p=preview

like image 94
Timothy Avatar answered Jan 11 '23 23:01

Timothy


since you use ng-bind-html you also need $sce, so my advice do it in your controller. Like so

Ctrl.$inject= ['$sce', '$filter', '$scope'];
Function Ctrl($sce, $filter, $scope) {
  $scope.content= $filter('limitTo')(dataWithHtml, 100, 0);
  $scope.content= $sce.trustAsHtml($scope.content);
}

on html you can use like so:

<p ng-bind-html="content"></p>

in this case I assume your original data is dataWithHtml, 100 is the limit number, 0 is the starting point. More details please refer to official documentations.

like image 33
Adi Prasetyo Avatar answered Jan 11 '23 23:01

Adi Prasetyo


integrate this link :

 <script src="https://code.angularjs.org/1.2.16/angular-sanitize.js"></script>

check if you have sanitize here

var adminApp = angular.module('adminApp', ['ngSanitize', ...,])

in your html you macke this code :

<p ng-bind-html="item.get('Content') | limitTo: 150"></td>
like image 45
Ait Friha Zaid Avatar answered Jan 11 '23 23:01

Ait Friha Zaid