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

前端 未结 8 789
自闭症患者
自闭症患者 2021-01-13 02:15

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

8条回答
  •  独厮守ぢ
    2021-01-13 02:34

    You can use custom directive and filters which will work same as ng-bind-html

    {{content | limitTo:200}}

    directive:

    .directive('toHtml', function($timeout,$sce) {
       return {
              restrict: 'A',
              link: function($scope, element, attrs, ctrl) {
                 $timeout(function() {
                    element.html($sce.getTrustedHtml(element[0].innerText) || '');
                 }, 200);
              }
             };
    })
    

    Truncate with ellipsis:

    {{content | limitWithEllipsis:200}}

    you need to use custom filter(limitWithEllipsis) with above directive

    .filter('limitWithEllipsis', function() {
              return function(input, limit, begin) {
                  var str='';
                    if (Math.abs(Number(limit)) === Infinity) {
                      limit = Number(limit);
                    } else {
                      limit = parseInt(limit);
                    }
                    if (isNaN(limit)) return input;
    
                    if (angular.isNumber(input)) input = input.toString();
                    if (!angular.isArray(input) && !angular.isString(input)) return input;
                    if(input.length<=limit) return input;
                    begin = (!begin || isNaN(begin)) ? 0 : parseInt(begin);
                    begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
    
                    if (limit >= 0) {
                      str=input.slice(begin, begin + limit);
                      return str.concat('....'); 
                    } else {
                      if (begin === 0) {
                         str=input.slice(limit, input.length);
                        return str.concat('....');
                      } else {
                         str=input.slice(Math.max(0, begin + limit), begin);
                        return str.concat('....');
                      }
                    }
                };
            })
    

提交回复
热议问题