简体   繁体   中英

autoscroll angularjs doesn't seem to work

Hi I'm building a chatapp in angularjs and I want the chatbox to scroll down automatically. I'm using this example that I put in a directive: http://jsfiddle.net/atRkJ/

It works as it is but when I use it with a ng-repeat it doesn't work.

html file

     <ul  id="chat" style="height:300px; overflow:auto" scroll-if>

            <li data-ng-repeat="messageinfo in messages" > 

                <div class="message-date">
                    {{messageinfo[0]}}
                </div>

            </li>

        </ul>

directive.js

  .directive('scrollIf', function() {
return{
    restrict: "A",
    link: function(scope, element, attributes) {
        var chat_height = $('#chat').outerHeight();
        console.log(chat_height);
        $('#chat').scrollTop(chat_height);
    }
   }
  });

Any help? Thanks

When you call the code:

var chat_height = $('#chat').outerHeight();
console.log(chat_height);
$('#chat').scrollTop(chat_height);

Your ng-repeat does not run and finish its rendering yet => the outerHeight returned is not correct.

You must run your code when the ng-repeat finishes. To do it, you could define another directive:

.directive('scrollItem',function(){
    return{
    restrict: "A",
    link: function(scope, element, attributes) {
        if (scope.$last){ // If this is the last item, trigger an event
           scope.$emit("Finished");
       }
    }
   }
});

Use it:

<li data-ng-repeat="messageinfo in messages" scroll-item>

Your scrollIf directive can now be notified when the ng-repeat completes

.directive('scrollIf', function() {
return{
    restrict: "A",
    link: function(scope, element, attributes) {
        scope.$on("Finished",function(){ //Handle an event when all the items are rendered with ng-repeat
            var chat_height = element.outerHeight();
            console.log(chat_height);
            element.scrollTop(chat_height); 
        });
    }
   }
  });

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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