網站顯示時,有時需要限制多少文字長度,然後後面加上…的需求
以下是參考stackoverflow使用ng來解決 :
擴充一個filter :
angular.module('ng').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 lastspace = value.lastIndexOf(' ');
if (lastspace != -1) {
//Also remove . and , so its gives a cleaner result.
if (value.charAt(lastspace-1) == '.' || value.charAt(lastspace-1) == ',') {
lastspace = lastspace - 1;
}
value = value.substr(0, lastspace);
}
}
return value + (tail || ' …');
};
});
使用上 :
{{some_text | cut:true:100:' ...'}}
參考 : http://stackoverflow.com/questions/18095727/limit-the-length-of-a-string-with-angularjs