2015-06-18 62 views
1

用下面的例子使用angular.element,我怎樣才能在每次點擊時滾動到ng-repeat中的下一個項目?滾動到下一個ng-repeat項目

這是我到目前爲止,我只是不知道下一步該怎麼做:

var app = angular.module('myApp', []); 

app.controller('MainController', ['$scope', function ($scope) { 

    $scope.items = [{ 
     name: "apple" 
    }, { 
     name: "pear" 
    }, { 
     name: "Avacado" 
    }, { 
     name: "Banana" 
    }]; 

    $scope.go = function ($event) { 
     console.log(angular.element($event.currentTarget).parent().next()); 
    }; 

}]); 

HTML:

<div ng-app="myApp"> 
    <div ng-controller="MainController"> 
    <div class="box" ng-repeat="item in items track by $index"> 
     <h3>{{item.name}}</h3> 
     <button ng-click="go($event)">go to next box</button> 
    </div> 
    </div> 
</div> 

http://jsfiddle.net/0bwcLfv4/2/

jQuery是包括在網站上已經,所以我當然希望每個卷軸的動畫。

回答

5

現在確定你想要得到多麼奇特。你可以做一些基本的東西,比如HTML定位標記。

<a name="section1">Section 1</a> 

一起

<a href="#section1">Go to section 1</a> 
+0

添加到這一點,你可以簡單地編號的部分(1,2,3)和使用綁定到通用點擊事件的計數器: $(document).click(function( ){counter ++; }); –

3

您可以在每個錨(我用的錨在這個例子中,因爲它更語義正確進行導航)將偵聽click事件和滾動自定義指令啓動相應的觀點。您使用下一個元素的索引來提供該指令,因此它知道滾動到的位置。

<div scroll-box> 
    <div ng-repeat="item in items ..."> 
     ... 
     <a scroll-to-next="{{ ($index + 1) % items.length }}">...</a> 
     <!-- make the last element point to the first one --> 
    </div> 
</div> 

scroll-box是一個包裝指令所述scroll-to-next指令將登錄其駐留的元件。這是爲了避免對元素進行查詢,它更多地是做事的「角色方式」。 而不是做查詢scroll-to-next指令將要求封裝使用給定的索引的下一個元素。

這是一個plunker與工作實施。

+0

工程就像一個魅力! – Beyers

2

對於平滑滾動,你可以使用動畫通過jQuery的偏移功能。


這是JsFiddle link


例如,

HTML

<div ng-app="myApp"> 
    <div ng-controller="MainController"> 
     <div class="box" id="box{{$index}}" ng-repeat="item in items track by $index"> 
      <h3>{{item.name}}</h3> 
      <button ng-click="go('#box' + ($index + 1))">go to next box</button> 
     </div> 
    </div> 
</div> 

我加id="box{{$index}}"來分配目標ID

JS

var app = angular.module('myApp', []); 

app.controller('MainController', ['$scope', function ($scope) { 

    $scope.items = [{ 
     name: "apple" 
    }, { 
     name: "pear" 
    }, { 
     name: "Avacado" 
    }, { 
     name: "Banana" 
    }]; 

    $scope.go = function(targetId){ 
     var destination = $(targetId).offset().top; 
     $('html, body').animate({scrollTop: destination}, 300); 
    }; 

}]); 


希望它能幫助。

0

使用下面的代碼

HTML:

<div ng-app="myApp"> 
    <div ng-controller="MainController"> 
    <div class="box" ng-repeat="item in items track by $index" id="question{{item.id}}"> 
     <h3>{{item.name}}</h3> 
     <button ng-click="go(item.id + 1)">go to next box</button> 
    </div> 
    </div> 
</div> 

控制器:

$scope.go = function (aid) { 

    $timeout(function() { 
    var idheight = $(window).height() + $('#question'+aid).position().top-100; 
    $('html, body').animate({scrollTop: idheight}, 1000); 
    }, 500); 

};