2016-10-17 26 views
0

我有一个异步调用retreived的项目列表,该列表显示在ng-repeat的帮助下。由于该列表的div容器具有固定的高度(400px),我希望滚动条位于底部。为此,我需要scrollHeight。但postLink中的scrollHeight不是最终的高度,而是最初的高度。如何获得async html attribut

ppChat.tpl.html

<!-- Height of "chatroom" is "400px" --> 
<div class="chatroom"> 
    <!-- Height of "messages" after all messages have been loaded is "4468px" --> 
    <div class="messages" ng-repeat="message in chat.messages"> 
    <chat-message data="message"></chat-message> 
    </div> 
</div> 

ppChat.js

// [...] 
compile: function(element) { 
    element.addClass('pp-chat'); 

    return function(scope, element, attrs, PpChatController) { 
    var messagesDiv; 
    // My idea was to wait until the messages have been loaded... 
    PpChatController.messages.$loaded(function() { 
     // ...and then recompile the messages div container 
     messagesDiv = $compile(element.children()[0])(scope); 
     // Unfortunately this doesn't work. "messagesDiv[0].scrollHeight" still has its initial height of "400px" 
    }); 
    } 
} 

有人能解释我错过了这里?

由于这里需要的是它

+0

亲切,创建一个plunkr,以便其他人可以编辑/改善你的代码。 –

+0

你从哪里得到2000px的滚动高度? – Sravan

回答

1

一个plunk你可以得到的div scrollHeight的DOM通过以下方式做更新后。

下面的指令在数组上设置一个监视,即一个集合,并使用$ timeout服务来等待DOM被更新,然后它滚动到div的底部。

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

function chatDirective($timeout) { 
    return { 
    require: 'chat', 
    scope: { 
     messages: '=' 
    }, 
    templateUrl: 'partials/chat.tpl.html', 
    bindToController: true, 
    controllerAs: 'chat', 
    controller: ChatController, 
    link: function(scope, element, attrs, ChatController) { 
     scope.$watchCollection(function() { 
     return scope.chat.messages; 
     }, function (newValue, oldValue) { 
     if (newValue.length) { 
      $timeout(function() { 
      var chatBox = document.getElementsByClassName('chat')[0]; 
      console.log(element.children(), chatBox.scrollHeight); 
      chatBox.scrollTop = chatBox.scrollHeight; 
      }); 
     } 
     }); 
    } 
    }; 
} 

更新的重击器是here

而且在你的控制器,你已经写成,

var Controller = this; 

    this.messages = []; 

这是更好用这种方式来写,这里VM代表视图模型

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

function AppController($timeout) { 
    var vm = this; 

    vm.messages = []; 

    $timeout(
    function() { 
     for (var i = 0; i < 100; i++) { 
     vm.messages.push({ 
      message: getRandomString(), 
      created: new Date() 
     }); 
     } 
    }, 
    3000 
); 
}