angularjs scroll to counter in ng-repeat

谁都会走 提交于 2019-12-11 05:03:26

问题


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


回答1:


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)                     
             }                 
        });
    }
  };
});


来源:https://stackoverflow.com/questions/18941970/angularjs-scroll-to-counter-in-ng-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!