【问题标题】:Replace text while outerHeight is > 30 in Angular DirectiveAngular 指令中的 outerHeight > 30 时替换文本
【发布时间】:2016-08-29 16:10:13
【问题描述】:

这发生在 Angular 指令链接函数内部。

所以我有这个工作,但我试图使用角度的指令 $element 做得更好。似乎我陷入了无限循环。我做错了什么 - 我认为这很容易,但我显然在这里遗漏了一些基本的东西。

这行得通:

$timeout(function(){
    $('.add-ellipsis').each(function() {
              var $ellipsisText = $(this);
              while ($ellipsisText.outerHeight() > 30) {
                $ellipsisText.text(function(index, text) {
                  return text.replace(/\W*\s(\S)*$/, '...');
                });
              }
            });
}, false);

示例:https://jsfiddle.net/rooksstrife/7chxph91/12/

尝试将其更改为: 注意($element.context.firstChild.firstElementChild.innerText = "一长串文本".

$timeout(function(){
          while ($element.outerHeight() > 30) {
           $element.context.firstChild.firstElementChild.innerText.replace(/\W*\s(\S)*$/, '...');
          }
    }, false);

【问题讨论】:

  • 为什么不使用 $watch 来注册 outerHeight 的变化?
  • @Luxor001不明白你的意思——我不需要观察不断变化的高度——只需要调整一次。如果这就是你所指的。

标签: javascript jquery angularjs angularjs-directive


【解决方案1】:

您可以为ellipsis 创建指令。

jsfiddle 上的示例。

angular.module("ExampleApp", [])
  .controller("ExampleController", function($scope) {

  })
  .directive('ellipsis', function() {
    return {
      restrict: "EA",
      scope: {
        ellipsis: "="
      },
      link: function(scope, element) {
        var $ellipsisText = $(element);
        while ($ellipsisText.outerHeight() > scope.ellipsis) {
          $ellipsisText.text(function(index, text) {
            return text.replace(/\W*\s(\S)*$/, '...');
          });
        }
      }
    };
  });
.card {
  max-width: 198px;
}
.title {
  text-align: center;
  font-size: 15px;
  color: #ffffff;
  height: 47px;
  max-height: 47px;
  overflow: hidden;
  width: 100%;
  padding: 0 10px;
}
.ell {
  vertical-align: middle;
  color: #000;
  text-decoration: none !important;
  border-bottom: 0 none;
  line-height: 1.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp" ng-controller="ExampleController">
  <div class="card">
    <div class="title">
      <a ellipsis="47" class="ell">AS THE SOUTH CAROLINA shifted stations during their first practice of August, new head coach Will Muschamp sang along to the tune blaring through the speakers that spoke to the entirety of the college football world. "CH-CH-CH-CH-CHANGES!" Its performer, David Bowie, is gone -- a reminder that time stops for no man.</a>
    </div>
  </div>

</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多