sdawson26
sdawson26

Reputation: 139

Angular & jQuery:horizontal scrolling a div from a controller or directive

I have an simple ng-repeat that is populating a large number of table columns inside of a wrapper with a overflow-x: auto style. The result is a horizontal scrollbar with a bunch of information like so: http://www.websitecodetutorials.com/code/photo-galleries/css-horizontal-scroller1-demo.php

Every time the scope's data changes, the table updates and refreshes with new columns of information. My question becomes.. how can I force it to scroll all the way to the end on every initialization? My first attempt was to build a directive like this and assign "scroller" as an attribute to the wrapper:

app.directive('scroller', function() {
  return {
    // Restrict it to be an attribute in this case
    restrict: 'A',
    // responsible for registering DOM listeners as well as updating the DOM
    link: function(scope, element, attrs) {
      $(this).animate({ scrollLeft: '+=5200' }, 800, function() { });
    }
  };
});

How can I make the controller re-load data and then 'scrollLeft" 100% to the end (in sequence)? I have managed to hack it in jQuery and make it scroll when other events fire, but this isn't optimal since it should be happening at the end of the update cycle.

Upvotes: 1

Views: 1915

Answers (1)

patorjk
patorjk

Reputation: 2182

The link function gets called right before the updated elements are added to the DOM, so that may be why your animation call isn't working. Try adding a timeout and see if that works:

app.directive('scroller', function($timeout) {
  return {
    // Restrict it to be an attribute in this case
    restrict: 'A',
    // responsible for registering DOM listeners as well as updating the DOM
    link: function(scope, element, attrs) {
      $timeout(function() {
        element.animate({ scrollLeft: '+=5200' }, 800, function() { });
      }, 1);
    }
  };
});

I didn't test this, but figured I'd post it in case it helps.

Upvotes: 2

Related Questions