AngularJS: how do I show ellipses using limitTo filter only when a string exceeds the limit
Well, if you want you can build a filter for this, but I would use ngIf
directive, as below:
(function() { 'use strict'; angular.module('app', []) .controller('mainCtrl', function() { var vm = this; vm.text = 'Really longer than 10'; });})();
<!DOCTYPE html><html ng-app="app"><head> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.7/angular.min.js"></script></head><body ng-controller="mainCtrl as ctrl"> Without limit: <span ng-bind="ctrl.text"></span> <hr> With limit: <span ng-bind="ctrl.text | limitTo:10"></span> <span ng-if="ctrl.text.length > 10">...</span></body></html>
Writing your own filter based on limitTo
is the best way to do this.
angular.module('your-module-name').filter('dotsFilter', [ '$filter', function ($filter) { /** * Shorten the input and add dots if it's needed * @param {string} input * @param {number} limit */ function dotsFilter(input, limit) { var newContent = $filter('limitTo')(input, limit); if(newContent.length < input.length) { newContent += '...'; } return newContent; } return dotsFilter; }]);
Use in view:
{{ model.longTextData | dotsFilter:10 }}