[英]Get “next” and “previous” items in AngularJS?
我使用ngRoute在單擊時將故事列表篩選為一個特定故事,如下所示:
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/stories', {
templateUrl: '/partials/stories.html',
controller: 'StoryListCtrl'
}).
when('/stories/:storyID', {
templateUrl: '/partials/story.html',
controller: 'StoryDetailCtrl'
});
}]);
效果很好,但是如何獲得“下一個”和“上一個”故事。 用戶需要能夠在故事之間左右滑動,但是我不能簡單地加載所有故事-我需要加載每個故事以及故事的任一側。 然后,當用戶以任意一種方式滑動時,一個故事將被刪除,而新故事將被添加。
Angular有可能嗎? 我已經瘋狂地搜索過,但無論如何都找不到在線參考。
謝謝你的時間!
您可以為此使用角度ng-swipe。 例如,假設您具有以下文件。
story.html
<div ng-swipe-left="nextStory()" ng-swipe-right="previousStory()" >
{{storyID}}
</div>
StoryDetailCtrl
myApp.controller('StoryDetailCtrl', function ($scope, $routeParams, $location) {
$scope.storyID = $routeParams.storyID;
$scope.nextStory = function () {
var storyID = $routeParams.storyID;
var path = 'stories/' + (storyID + 1 );
$location.path(path);
//console.log("This is left Swipe.");
};
$scope.previousStory = function () {
var storyID = $routeParams.storyID;
var path = 'stories/' + (storyID - 1 );}
$location.path(path);
//console.log("This is right Swipe.");
};
});
確保在模塊中將ngTouch作為依賴項注入為['ngTouch']
希望這對您有意義。
當用戶滑動時,您需要發送帶有當前ID和方向的查詢,這樣,您將知道“正確的是下一個”和“左邊的”(如果是以前的話),也就是說您可以查詢
正確:比您當前的ID大1
左:比您當前的ID小1
無方向:僅加載當前ID
對於刷卡,您還可以使用$ swipe服務,ngSwipeLeft和ngSwipeRight。
您可以在傳遞/ stories /:storyID之前通過傳遞ID和方向來解析功能,也可以修改路由以支持方向,例如/ stories /:storyID /:orientation,並且方向可以為null
看看這個文章 ,你可能有作為一個例子,我只是想強調的是如何計算的當前頁和angularjs的刷卡功能,可能適用於您的方案。
angular.module('website', ['ngAnimate', 'ngTouch'])
.controller('MainCtrl', function ($scope) {
/* Code omitted */
$scope.direction = 'left';
$scope.currentIndex = 0;
$scope.setCurrentSlideIndex = function (index) {
$scope.direction = (index > $scope.currentIndex) ? 'left' : 'right';
$scope.currentIndex = index;
};
$scope.isCurrentSlideIndex = function (index) {
return $scope.currentIndex === index;
};
$scope.prevSlide = function () {
$scope.direction = 'left';
$scope.currentIndex = ($scope.currentIndex < $scope.slides.length - 1) ? ++$scope.currentIndex : 0;
};
$scope.nextSlide = function () {
$scope.direction = 'right';
$scope.currentIndex = ($scope.currentIndex > 0) ? --$scope.currentIndex : $scope.slides.length - 1;
};
})
干杯!
假設您有一個要在/stories
頁面中顯示的故事列表,現在使用<a ng-href="yourCtrl.getStoryHref()" />Full Story</a>
; 現在,您將轉到顯示完整故事的故事頁面。 在這里,您具有上一個和下一個鏈接,這些鏈接將帶您到上一個/下一個故事<a ng-href="yourCtrl.getNextStoryHref()" />Next Story</a>
和<a ng-href="yourCtrl.getPrevStoryHref()" />Previous Story</a>
或者,如果您想在移動設備上使用它,則可以使用ng-touch或fastclick。 在ng-touch中,您可以使用ng-swipe-left
和ng-swipe-right
<!-- Your Story Div -->
<div ng-swipe-right="yourCtrl.moveToNextStory">Content</div>
在控制器內部的moveToNextStory函數中,將$ location.path設置為下一個故事的路徑
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.