I have an Angular Bootstrap select plugin applied to my select menus, which renders the selected menu item into the following:
<button data-toggle="dropdown" class="btn btn-default dropdown-toggle" type="button">
<div class="filter-option pull-left">Item with a very long name</div> <div class="caret"></div>
</button>
I'm trying to develop a function that will truncate a selected menu item name if it is greater than a specified length.
The function:
$scope.truncate = function(){
var maxLength = 5;
$('button .filter-option').text(function(i, text) {
if (text.length > maxLength) {
return text.substr(0, maxLength) + '...';
}
});
}
The function called on the original select markup in the Angular template:
<select
class="nya-selectpicker"
ng-model="items"
ng-options="g.name for g in myItems"
ng-change="truncate()">
<option value="">Select</option>
</select>
My issue: It's not truncating the item I selected from my menu; it's truncating the default items of the two adjacent select menus in my template.
How can I update this function to truncate the item I select from my menu?
So essentially you need to create a filter. You can then apply this filter in the ng-options
.
ng-options="(g.name | myFilter) for g in myItems"
myApp.filter('myFilter', function() {
return function(val) {
var maxLength = 5;
if (val > maxLength) {
return val.substr(0, maxLength) + '...';
} else {
return val;
}
};
});
You could instead apply a filter to the array (I like the previous example better)
ng-options="g.name for g in myItems | myFilter"
myApp.filter('myFilter', function() {
var maxLength = 5;
return function(arr) {
var returnArr = [];
for(var i = 0; i < arr.length; i++) {
(function() {
var item = {};
angular.copy(arr[i], item);
if (item.name > maxLength) {
item.name = item.name.substr(0, maxLength) + '...';
}
returnArr.push(item);
})();
}
return returnArr;
};
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.