[英]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.