问题描述
我只想在文本被截断时显示有角度的 UI 引导工具提示.我用自定义指令尝试了下面的代码
I want to show angular UI bootsrap tooltip only when the text is truncated.I tried the below code with custom directive
<div tooltip="{{value}}" tooltip-append-to-body="true" enable-truncate-tooltip>{{value}}</div>
.directive("enableTruncateTooltip", function () {
return {
restrict: 'A',
link: function (scope, elem, attr) {
elem.bind('mouseenter', function () {
var $this = angular.element(this);
if (this.offsetWidth >= this.scrollWidth) {
angular.element('.tooltip').attr('hide-tooltip', true);
}
});
}
}
})
它在 angular-ui-bootstrap 版本 0.12.1 中运行良好.但是后来的版本不支持这个.
It works fine in angular-ui-bootstrap version 0.12.1. But later versions are not supporting this.
如何在最新版本的 angular-ui-bootstrap 中实现同样的功能?
How can i achieve this same functionality in latest version of angular-ui-bootstrap?
预先感谢您的帮助.
推荐答案
TL;DR: Plunker 演示(使用 $watch)
(答案已更新以反映使用 $watch 而不是 $timeout 的建议,感谢您的评论 迈克尔·米什·基西连科!)
首先,将您的 angular-ui 指令更改为更新的指令(前缀为 'uib-'):
First of all, change your angular-ui directives to the updated ones (prefix with 'uib-'):
<div uib-tooltip="{{value}}" show-tooltip-on-text-over-flow tooltip-enable="false">{{value}}</div>
然后使用下面的指令,它动态地改变angular-ui提供的特性tooltip-enable
(注意你应该用指令tooltip-enable="false"
所以如果文本没有被截断,工具提示将被禁用:
And then use the following directive, which dynamically changes the angular-ui provided feature tooltip-enable
(note that you should initialize the element with directive tooltip-enable="false"
so the tooltip will be disabled if the text is not truncated:
myApp.directive("showTooltipOnTextOverflow", ["$timeout", function($timeout) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var el = element[0];
scope.$watch(function(){
return el.scrollWidth;
}, function() {
var el = element[0];
if (el.offsetWidth < el.scrollWidth) {
//console.log('ellipsis is active for element', element);
attrs.tooltipEnable = "true";
} else {
//console.log('ellipsis is NOT active for element', element);
}
});
/*$timeout(function() {
var el = element[0];
if (el.offsetWidth < el.scrollWidth) {
//console.log('ellipsis is active for element', element);
attrs.tooltipEnable = "true";
} else {
//console.log('ellipsis is NOT active for element', element);
}
});*/
}
};
}]);
要截断文本,我将使用纯 CSS:
To truncate the text i'll use plain CSS:
span.truncated {
width: 400px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
这篇关于仅当文本在 angular UI bootstrap 指令中被截断时才显示工具提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!