我有angularjs app。我添加了下拉列表,但如果选项名称太长,则下拉列表的宽度会增加,随着项目数量的增加,其高度也会不断增加。我创建了jsfiddle来展示我到目前为止能够实现的目标。 http://jsfiddle.net/ibha/jd9jk755/4/
<div ng-controller="MyCtrl">
<select class="scrollwidth">
<option ng-class="scrollwidth" ng-repeat="p in optionList" value="{{p.name}}">
{{p.name}}
</option>
</select>
</div>
function MyCtrl($scope) {
$scope.optionList = [{name : 'vlist3'},{name : 'vlist1'},{name : 'vlist2'},{name : 'vlistLongNameeeeeeeeeeeeeeeeeeeeeeeeeee'}];
}
请告诉我如何使下拉列表的宽度和高度保持不变并添加滚动条。
答案 0 :(得分:0)
不幸的是,浏览器正在做什么,你无法改变它,我所知道的唯一解决方案是自己截断实际文本。
您可以为此创建一个过滤器(这是一个示例):
angular.module('myApp', [])
.filter('truncate', function () {
return function (input, characters) {
if (input.length > characters) {
return input.substr(0, characters) + '...';
}
return input;
};
}).controller('MyCtrl', function MyCtrl($scope) {
$scope.optionList = [{
name: 'vlist3'
}, {
name: 'vlist1'
}, {
name: 'vlist2'
}, {
name: 'vlistLongNameeeeeeeeeeeeeeeeeeeeeeeeeee'
}];
});
工作示例:
答案 1 :(得分:0)
我很快将其与ngRepeat:http://jsfiddle.net/jshado1/nfkgp5nL/
一起扔了HTML
<select
class="truncated-select">
<option
ng-repeat="option in options"
value="{{option.value}}"
truncate-option="option.label">{{option.label}}</option>
</select>
角
angular.module('MyApp', [])
.controller('MyController', [
'$scope',
function MyController( $scope ) {
$scope.options = [
{
"label": "1label",
"value": "option1value"
},
{
"label": "option2label",
"value": "option2value"
},
{
"label": "option3label",
"value": "option3value"
}
];
$scope.myModel = $scope.options[0];
}
])
.directive('truncateOption', function truncateOption() {
return {
restrict: 'A',
scope: {
label: '=truncateOption'
},
link: function postLink(scope, element) {
var selectElm = element.parent(),
maxWidth = selectElm.css('max-width').replace('px',''),
fontSize = selectElm.css('font-size').replace('px',''),
maxLength = Math.floor(maxWidth / fontSize);
if ( scope.label.length > maxLength )
scope.label = scope.label.slice( 0 , maxLength-1 ) + '…';
}
};
});
通过上述内容,它会在选项标签中的select:max-width
= 10个字符上尊重max-width: 10em
的值。