angularjs - 仅当文本在 angular UI bootstrap 指令中被截断时才显示工具提示

标签 angularjs tooltip angular-ui-bootstrap

我只想在文本被截断时显示 Angular UI 引导工具提示。
我用自定义指令尝试了下面的代码

<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 .但是后来的版本不支持这个。

如何在最新版本的 angular-ui-bootstrap 中实现相同的功能?

在此先感谢您的帮助。

最佳答案

TL;博士 :Plunker Demo (using $watch) Old demo (using $timeout)

(答案已更新以反射(reflect)使用 $watch 而不是 $timeout 的建议,感谢您的评论 Michael Mish Kisilenko!)

首先,将您的 angular-ui 指令更改为更新的指令(前缀为“uib-”):

<div uib-tooltip="{{value}}" show-tooltip-on-text-over-flow tooltip-enable="false">{{value}}</div>

然后使用以下指令,它会动态更改 angular-ui 提供的功能 tooltip-enable (请注意,您应该使用指令 tooltip-enable="false" 初始化元素,因此如果文本未被截断,工具提示将被禁用:
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:
span.truncated {
    width: 400px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

关于angularjs - 仅当文本在 angular UI bootstrap 指令中被截断时才显示工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35296022/

相关文章:

javascript - AngularJS:编译与模板

javascript - 如何在 angular-bootstrap-datetimepicker 输入字段中显示自定义日期格式?

javascript - Highcharts - 如何在工具提示中隐藏系列名称和 Y 值

css - 样式化 Bootstrap 工具提示上的箭头

angularjs - orderBy 可以与 AngularUI typeahead 一起使用吗?

Javascript/JSON : Object of object converted to associative array

javascript - Angular 在外部 Controller 中使用带有对象的 jQuery 插件

javascript - nvd3 piechart.js - 如何编辑工具提示?

javascript - 指令 'uibCarousel' 要求的 Controller 'uibSlide' 包装时找不到

javascript - Angular uib-typeahead 无法正常工作