1

Need to scroll to specific element in a list if $index == $scope.counter of ng-repeat.

HTML:

<button type="button" ng-click="findA()">FIND TYPE A</button>
<button type="button" ng-click="findB()">FIND TYPE B</button>    
<ul class="feeds">
  <li ng-repeat="m in mList" ng-class="showActive($index)">{{m.s}}</li>
</ul>

JS: CONTROLLER:

$scope.shouldScroll = true; 

$scope.mList=[{"s":3},{"s":23},{"s":33},{"s":12},{"s":31},{"s":231}];
$scope.showActive =function(index){
        /* only if scope.counter == index ,, then set the class,, 
NEED : to scroll to this element where index == counter */
   if(index == $scope.counter){
       return 'activeMarkClass';
   }
   return '';
}

$scope.findA =function(){
   $scope.counter=2;
}
$scope.findB =function(){
   $scope.counter=5;
}

PROBLEM :

Whenever the findA and findB is called the css class of li is changed on counter, using showActive. But I also want to scroll to this element counter. So when findA is called i want to scrollTo the the 2nd item and to the 5th item when findB is called. Tried directives but couldn't understand how counter will be used there.

NOTE : the counter is also used by some other methods in the controller. So can't move counter completely in the directive. Also DON'T want to do anchor scroll since already having routing url there, need a window scroll/scrollTo

shrw
  • 1,719
  • 5
  • 27
  • 50

1 Answers1

2

You've to write a directive for that and watch for counter to update. As soon as it updates, your directive finds the element by index (counter) and scrollTo it.

Here is a demo: http://jsfiddle.net/ZdunA/1/

myApp.directive('scrollTo', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
         var $body = $('body');
         scope.$watch('counter', function(newVal, oldVal) {
             if (newVal && newVal !== oldVal) {
                 $body.scrollTop(element.find('li').eq(newVal).position().top)                     
             }                 
        });
    }
  };
});
codef0rmer
  • 10,284
  • 9
  • 53
  • 76