Truncate Filter for AngularJS v1
This is a custom filter to truncate text. It gives you the possibility to specify the length and the end string of the text.
by Ravindra Athreya
HTML
<div ng-app="myApp">
<h2>Truncate Filter Example</h2>
<div>
<input type="text" ng-model="myText" placeholder="add your text here" />
</div>
<div>
<h3>Output:</h3>
<p>{{myText|truncate}}</p>
<p>{{myText|truncate:5}}</p>
<p>{{myText|truncate:25:" ->"}}</p>
</div>
</div>
CSS
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.angularjs.org/angular-1.0.0rc6.min.js"></script>
<style>
JavaScript
// add the filter to your application module
angular.module('myApp', ['filters']);
/**
* Truncate Filter
* @Param text
* @Param length, default is 10
* @Param end, default is "..."
* @return string
*/
angular.module('filters', []).
filter('truncate', function () {
return function (text, length, end) {
if (isNaN(length))
length = 10;
if (end === undefined)
end = "...";
if (text.length <= length || text.length - end.length <= length) {
return text;
}
else {
return String(text).substring(0, length-end.length) + end;
}
};
});
/**
* Usage
*
* var myText = "This is an example.";
*
* {{myText|Truncate}}
* {{myText|Truncate:5}}
* {{myText|Truncate:25:" ->"}}
* Output
* "This is..."
* "Th..."
* "This is an e ->"
*
*/