在outerHeight为>时替换文本。角度指令中的30

时间:2016-08-29 16:10:14

标签: javascript jquery angularjs angularjs-directive

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

所以我有这个工作,但我试图使用angular的指令$元素做得更好。看来我陷入无休止的循环中。我做错了什么 - 我认为这很容易,但我显然在这里缺少一些基本的东西。

这有效:

$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);

1 个答案:

答案 0 :(得分:0)

您可以为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>