Skip to content

Instantly share code, notes, and snippets.

@Davids89
Created September 17, 2015 07:36
Show Gist options
  • Save Davids89/15ea10cac85bb80df780 to your computer and use it in GitHub Desktop.
Save Davids89/15ea10cac85bb80df780 to your computer and use it in GitHub Desktop.
Angular.js filter to reduce a word to the last space and add a '...' at the end
app.filter('cut', function(){
return function(value, wordwise, max, tail){
if(!value)
return ' ';
max = parseInt(max, 10);
if(!max)
return value;
if(value.length <= max)
return value;
value = value.substr(0, max);
if(wordwise){
var indexs = [];
for(var i = 0; i < value.length; i++){
if(value[i].indexOf(' ') != -1){
indexs.push(i);
}
}
var lastspace = indexs[indexs.length - 1];
console.log(value, indexs);
if(lastspace != -1){
value = value.substr(0, lastspace);
}
}
return value + (tail || ' ...');
};
});
@Davids89
Copy link
Author

To use it in the view {{ word | cut:true:30:' ...'}}

When:

  • value: is the word you want to cut.
  • wordwise: if it's true you reduce the word.
  • max: max length you want to show.
  • tail: by default is ' ...' but you can use what you want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment