angular 写 文字省略显示指令

在一个表格中,假设有一栏数据非常多,如果在页面中完全显示该数据,则会导致表格非常难看,宽窄高低不一。

效果如下图:

 

很明显这是不美观的,非常影响用户体验。为了达到更好的效果,我们需要下面的页面:

 

当点击省略号后,出现完整的内容:

 

为了达到这样的目的,在JS中创建 shortWords 指令:

//创建文字缩略显示指令,当文字内容长于一定数量时,缩略显示。
app.directive("shortWords", function() {
var editorTemplate = '<span class="short-words">' +
'<span>' +
'{{view.shortText}}' +
'<a ng-click="toggleStatus()" ng-show="view.isNeeded"> ....</a>' +
'</span>' +
'<div ng-show="view.isShowed" class="full-content">' +
'<a href="#" onclick="return false;" ng-click="view.isShowed=false" class="close-full pull-right">&times;</a>' +
'<div>{{textContent}}</div>' +
'</div>' +
'</span>';

return {
restrict: "AE",
replace: true,
template: editorTemplate,
scope: {
textContent: "=",
maxLength : "="
},
controller: function($scope) {
$scope.view = {
isNeeded: $scope.textContent.length>$scope.maxLength,
shortText: $scope.textContent.length<$scope.maxLength?$scope.textContent:$scope.textContent.substring(0,$scope.maxLength-3),
isShowed: false
};

$scope.toggleStatus = function() {
$scope.view.isShowed = !$scope.view.isShowed;
};
}
};
});

然后在HTML页面中调用该指令,比如说要在表格的单元格中:
<td> <short-words text-content="caseData.DGSResult" max-length="40"></short-words> </td>

从以上可以看出,该指令需要接收两个参数,一个是text-content即文本内容,另一个max-length即显示的最大长度。当文本内容的长度超过自定的最大长度,就会进行省略显示。

PS:text-content文本内容需要angular传值过来。

相应的CSS:
.short-words{
display:inline-block;
min-width:130px;
position:relative;
}
.full-content{
position:absolute;
right:0;
width:200px;
background:rgba(244,254,254,0.9);
border-radius:4px;
border:1px solid #999;
padding:10px;
z-index:999;
}

.close-full{
font-size:20px;
}
以上内容都用在自己做的项目中。目前还没有动画效果。有待进一步改进。

 

posted on 2017-04-20 16:47  32岁学编程  阅读(425)  评论(0编辑  收藏  举报

导航