AngularJS - How to query the DOM when directive rendering is complete

前端 未结 2 1631
一个人的身影
一个人的身影 2020-12-10 00:18

I\'m trying to implement a custom scroll pane component using an AngularJS directive. in the following jsfiddle example I have an example of the basic prototype.

her

相关标签:
2条回答
  • 2020-12-10 00:59

    Two observations:

    • you don't need compile imho, but link function
    • you should wait until the element is ready, instead of using timeout

    So:

    myApp.directive('lpScrollPane', function factory() {
      return {
        restrict: 'A',
        replace: true,
        transclude: true,
        template: '<div class="scrollPaneWrapper"><div class="scrollPane" ng-transclude></div><div class="thumbTrack" ></div></div>',
        link: function (scope, iElement, iAttrs) {
          var minHeight = 30;
          var thumbTrack = angular.element(iElement.children()[1]);
    
          scope.onScrollHeight = function () {
            console.log(iElement.children()[0].scrollHeight);
    
            var H1 = iElement[0].offsetHeight;
            var H2 = iElement.children()[0].scrollHeight;
            if (H2 > H1) {
              var trackHeight = Math.round(minHeight + (H1 - minHeight) * (1 - Math.pow((H2 - H1) / H2, 0.8)));
              thumbTrack.css({
                display: "block",
                height: trackHeight + "px"
              });
              console.log(H2, H1, trackHeight);
            } else {
              thumbTrack.css({
                display: "none"
              });
            }
          };
    
          iElement.ready(function () {  
             scope.$watch(function () {
               scope.onScrollHeight();
             });
          });        
        }
      };
    });
    

    See jsFiddle.

    Edit:

    Because 2 images say more than 1000 words, here are two screenshots: last element still viewable gets inserted first element not viewable gets inserted

    0 讨论(0)
  • 2020-12-10 01:04

    See is there a post render callback for Angular JS directive?

    Unfortunately, there is no way to determine when rendering is complete (e.g., there is no event). Using $timeout seems to be the best workaround available.

    In the link above, @Nik mentioned in a comment that he was checking $('tr').length > 3, for his particular scenario, to determine when rendering was complete. Maybe there is something you could periodically examine in the DOM to determine that rendering is complete.

    0 讨论(0)
提交回复
热议问题