【问题标题】:angularjs scroll to counter in ng-repeatangularjs滚动以反击ng-repeat
【发布时间】:2014-09-18 20:17:47
【问题描述】:

如果$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: 控制器:

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

问题:

每当findAfindB 被调用时,li 的css 类就会在counter 上更改,使用showActive。但我也想滚动到这个元素计数器。因此,当调用 findA 时,我希望 滚动到第二个项目,并在调用 findB 时滚动到第五个项目。尝试了指令,但不明白如何在那里使用计数器。

注意:计数器也被控制器中的一些其他方法使用。所以不能在指令中完全移动counter。另外不要想要做锚滚动,因为那里已经有路由网址,需要window scroll/scrollTo

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    您必须为此编写指令并注意counter 的更新。一旦更新,您的指令就会通过索引(计数器)和scrollTo 查找元素。

    这是一个演示: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)                     
                 }                 
            });
        }
      };
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 2017-02-02
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多