简体   繁体   English

在angular Directive中outerHeight> 30时替换文本

[英]Replace text while outerHeight is > 30 in Angular Directive

This takes place inside of an Angular directive link function. 这发生在Angular指令链接函数内部。

So I have this working, but I was trying to use the angular's directive $element to do it one better. 所以我有这项工作,但是我试图使用angular的指令$ element做得更好。 It seems I get stuck in an endless loop. 看来我陷入了无休止的循环。 What I am I doing wrong - I thought it would be easy, but I am obviously missing something fundamental here. 我做错了-我认为这很容易,但是显然我在这里缺少一些基本知识。

This works: 这有效:

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

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

Trying to change it to: To note ($element.context.firstChild.firstElementChild.innerText = "a long string of text". 尝试将其更改为:注意($ element.context.firstChild.firstElementChild.innerText =“一长串文本”。

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

You can create directive for ellipsis . 您可以为ellipsis创建指令。

Example on jsfiddle . 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM