angular.module('app.component', []).directive('select', function () {
return {
restrict: 'E',
scope: {
currentValue: '=',
list: '=',
isDisabled: '=',
select: '&onSelec'
},
templateUrl: 'select.html',
replace: true,
link($scope) {
const id = new Date().getTime().toString()
$scope.id = $scope.id || `e-tax-cloud-select${id}`
$scope.currentValue = $scope.currentValue || {}
$scope.list = $scope.list || []
$scope.isShow = false
$scope.toggleList = () => {
if (!$scope.isDisabled) {
$scope.isShow = !$scope.isShow
}
}
$scope.chooseItem = (item) => {
if ($scope.currentValue !== item) {
$scope.currentValue = item
if (typeof $scope.select === 'function') {
$scope.select()
}
}
$scope.toggleList()
}
},
}
})
页面代码:
<div class="select" ng-class="{ disabled: !!isDisabled, 'have-list': isShow }" id="{{id}}" ng-mouseleave="isShow = false"> <div class="select-label" ng-click="toggleList()">
<span class="text" title="{{currentValue[name]}}">{{currentValue[name]}}</span>
<span class="icon icon-arrow-{{isShow ? 'up' : 'down'}}"></span>
</div>
<ul class="select-list" ng-show="isShow">
<li ng-repeat="item in list track by $index" ng-class="{ active: item[key] === currentValue[key], disabled: !!item.disabled }" ng-click="chooseItem(item)" >
<span title="{{item[name]}}">{{item[name]}}</span>
</li>
</ul>
</div>
样式:
.select { position: relative; width: 100%; height: 32px; line-height: 32px; color: #666; cursor: pointer; box-sizing: border-box;border: 1px solid #dbdbdb; border-radius: 6px;
&.disabled { cursor: not-allowed; }
.select-label { display: inline-flex; width: 100%;
.text { width: calc(100% - 20px); text-align: left;padding-left: 8px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .icon { width: 20px; text-align: right; padding-right: 8px;} }
.select-list { position: absolute; top: 32px; left: 0; width: 100%; min-width: 120px; min-height: 32px; max-height: 320px; overflow-y: auto; z-index: 9999; box-shadow: 0px 1px 5px 0px rgba(0,0,0,0.1); border: 1px solid #dbdbdb; border-radius: 8px; background-color: @background-color;
li { width: 100%; height: 32px; line-height: 32px; text-align: left; padding: 0 8px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
&.active { background-color: #efef69; color: #fff; }
&:hover { color: #000; background-color: #232323; }
&.disabled { cursor: not-allowed; } } }
&.have-list { border-bottom: none; border-bottom-left-radius: 0; border-bottom-right-radius: 0; .select-list { border-top-left-radius: 0; border-top-right-radius: 0; } } }