Angular 更新多个元素高度以匹配最高元素的指令

Angular directive to update height of multiple elements to match the tallest

我对 Angular 的指令还很陌生,正在尝试找出使用它们的正确方法。我正在使用 ng-repeat 来填充元素列表。加载中继器后,我想查看每个元素并找出哪个元素最高(其中包含最多的文本),然后将所有元素强制为该大小。

在 jQuery 中完成此操作的方法如下:

var tallest = 0;
// Loop through each element
$('.element-class').each(function () {
    var thisHeight = $(this).height();      
    if (thisHeight > tallest)
        tallest = thisHeight;
});
// Apply height to all elements
$('.element-class').height(tallest);

有人可以指导我如何使用指令(或其他更合适的 Angular 方式)完成此操作。中继器看起来像这样。

<div class="element-class" ng-repeat="item in items">
    <div class="element-title" ng-bind="item.title"></div>
    <p class="element-text" ng-bind="item.description"></p>
</div>

您需要 运行 您的代码正好在 ng-repeat 最后一个元素呈现在视图上之后。

Angular 解决方案如下所示。

HTML

<div class="element-class" on-finish-ng-repeat-render ng-repeat="item in items">
    <div class="element-title" ng-bind="item.title"></div>
    <p class="element-text" ng-bind="item.description"></p>
</div>

指令

app.directive('onFinishNgRepeatRender', function($timeout) {
    return {
        restrict: 'A',
        link: function(scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function() {
                    //this coade will execute right after ng-repeat rendering has been completed
                    var tallest = 0, currentElement = angular.element(element);
                    // Loop through each element
                    angular.forEach(angular.element(element), function(value, key) {
                        var thisHeight = angular.element(value).height();
                        if (thisHeight > tallest)
                            tallest = thisHeight;
                    });
                    // Apply height to all elements
                    currentElement.height(tallest);
                });
            }
        }
    }
});

希望对您有所帮助,谢谢。

您可以执行以下操作。使用指令,您可以跟踪每个元素,并在最后一个元素上调用一个函数,该函数将计算每个元素的高度并找到最高的元素,然后将所有元素设置为该高度。您将需要使用 angular 的 $timeout 以确保在 angular 完成对 dom 的操作之前不检查高度。这是一些代码,下面我放了一个 link to a plunker.

HTML

<div equalize-height>
  <div class="element-class" equalize-height-add="item" ng-repeat="item in items">
    <div class="element-title" ng-bind="item.title"></div>
    <p class="element-text" ng-bind="item.description"></p>
  </div>
</div>

Angular

.directive('equalizeHeight', ['$timeout', function($timeout){
return {
  restrict: 'A',
  controller: function($scope){
    console.log('equalizeHeightFor - controller');
    var elements = [];
    this.addElement = function(element){
      console.log('adding element:', element);
      elements.push(element);
      console.log(elements);
    }

    // resize elements once the last element is found
    this.resize = function(){
      $timeout(function(){
        console.log('finding the tallest ...');
        // find the tallest
        var tallest = 0, height;
        angular.forEach(elements, function(el){
          height = el[0].offsetHeight;
          console.log('height:', height);
          if(height > tallest)
            tallest = height;
          // console.log(el);
        });
        console.log('tallest:', tallest);
        console.log('resizing ...');
        // resize
        angular.forEach(elements, function(el){
          el[0].style.height = tallest + 'px';
        });
        console.log('-- finished --');
      }, 0);
    };
  }
};
}])

.directive('equalizeHeightAdd', [function($timeout){
return {
  restrict: 'A',
  require: '^^equalizeHeight',
  link: function(scope, element, attrs, ctrl_for){
    console.log('equalizeHeightAdd - link');
    // add element to list of elements
    ctrl_for.addElement(element);
    if(scope.$last)
      ctrl_for.resize();
  }
};
}])

这里有一个 link 给 plunker 也可以看到它的实际效果: http://plnkr.co/edit/X4jmwZ?p=preview

我也想这样做。这个线程对我帮助很大。经过一些麻烦后,我找到了解决方案。

我想做的是获取所有元素的长度并将所有元素长度设置为最高。

所以首先我需要检测 ng-repeat 何时通过指令完成加载,并且在该指令中,一旦我检测到最后一个已经完成加载,我必须找到所有元素的最大长度和将其应用于所有元素。

HTML

<div class="col-lg-4" ng-repeat="category in categoriesList.categories" set-max-height> 
  <div class="catagory-item">
    <h1 class="text-center">{{category}}</h1>
  </div>
</div>

1) set-max-height 是一个指令名。 2) category-item 是 class,通过使用这个 class 名称,我想获取所有元素的高度并将其设置为所有元素的最大高度。

指令

app.directive('setMaxHeight', ['$timeout',function($timeout) {
return {
    link: function ($scope, $element, $attrs) {
        //Belove code will run afer ng-repeat finished
        if ($scope.$last){

            //Get all element by class name
            var elements = document.getElementsByClassName("catagory-item");
            var maxHeight = 0;

            $timeout(function(){
                // Get the max height from all div
                for (var i = 0; i < elements.length; i++) {
                   var elementHeight = elements[i].offsetHeight;
                   if (elements[i].offsetHeight > maxHeight) {
                       maxHeight = elementHeight;
                   }
                }
                // set max height to the all div
                for (var i = 0; i < elements.length; i++) {
                    elements[i].style.height = maxHeight + "px"; 
                }   
            });

        }
    }
}
}]);

很有魅力(谢谢!)

但是如果你计划在重复的中间过滤或添加新元素,你应该在 'equalizeHeightAdd' 指令的末尾松开 'if'(否则它不会自行调整大小) 并在控制器上实现删除功能,并在元素被销毁时将其删除:

    .directive('equalizeHeight', equalizeHeight)
    .directive('equalizeHeightAdd', equalizeHeightAdd);

    equalizeHeight.$inject = ['$timeout'];

    /* @ngInject */
    function equalizeHeight() {
        var directive = {
            bindToController: true,
            controller: ControllerName,
            controllerAs: 'vm',
            link: link,
            restrict: 'A',
            scope: {}
        };
        return directive;

        function link(scope, element, attrs) {

        }
    }

    ControllerName.$inject = ['$window', '$timeout'];

    /* @ngInject */
    function ControllerName($window, $timeout) {
        var elements = [];
        this.addElement = addElement;
        this.removeElement = removeElement;
        this.resize = resize;

        activate();

        function activate() {
            angular.element($window).on('resize', function () {
                angular.forEach(elements, function(el){
                    el[0].style.height = null;
                });
                resize();
            });
        }

        function addElement(element){
            elements.push(element);
            console.log(elements.length);
        }

        function removeElement(element){
            elements.splice(elements.indexOf(element),1);
        }

        // resize elements once the last element is found
        function resize(){
            $timeout(function(){
                // find the tallest
                var tallest = 0, height;
                angular.forEach(elements, function(el){
                    height = el[0].offsetHeight;
                    if(height > tallest)
                        tallest = height;
                });
                // resize
                angular.forEach(elements, function(el){
                    el[0].style.height = tallest + 'px';
                });
            }, 0);
        }
    }

    /* @ngInject */
    function equalizeHeightAdd(){
        return {
            restrict: 'A',
            require: '^^equalizeHeight',
            link: function(scope, element, attrs, ctrl_for){
                // add element to list of elements
                ctrl_for.addElement(element);
                ctrl_for.resize();
                element.on('$destroy', function () {
                    ctrl_for.removeElement(element);
                    ctrl_for.resize();
                });
            }
        };
    }

Sorry, I can not add comment to his answer, because of the lack of reputations, but I think this is a pretty important addition. Also sorry for the different formating, but this is how I use it in my project, but basically it's the same.