d1du d1du - 1 year ago 244
AngularJS Question

AngularJS: how do I show ellipses using limitTo filter only when a string exceeds the limit

I am using the limitTo filter on some strings. If the string is less than, say, 10 characters, then the string is displayed as is. If the string is longer than 10 characters, I want to display ellipses after cutting off the string at the tenth character. Is there an angular shortcut to doing this? Thanks

for example:

{{main.title | limitTo:10}}

if main.title = "A Good Day", the output would be: A Good Day

if main.title = "A Terrible Day", the output would be: A Terrible...

Answer Source

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($scope) {
      $scope.text = "Really longer than 10";
<!DOCTYPE html>
<html ng-app="app">

  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>

<body ng-controller="mainCtrl">
  Without limit: <span ng-bind="text"></span>
  With limit: <span ng-bind="text | limitTo:10"></span>
  <span ng-if="text.length > 10">...</span>