Angular previous/next 详细页面上的按钮和通过参数路由

Angular previous/next buttons on detail page and routing via parameters

到目前为止,我已经创建了 this plunker 个项目。

我最大的问题是 'Next/Previous' 项目按钮,它的功能在一定程度上但是有两个问题。

首先,过滤数据和索引似乎有些不匹配。 为了说明这一点,请打开 'Painting' 画廊,您将按预期看到按 year 列出的项目。但是,当在详细视图中的项目之间导航时,它们仅按它们在 json 对象中出现的顺序列出,并且分页仅部分起作用。

'Drawing' 库中的项目列表已在 json 文件中按时间顺序排列,因此该库似乎按预期工作。

其次,我显示 prev/next 按钮的方式似乎很老套,但这是迄今为止我能够让它工作的唯一方式。

这是我的列表和详细视图控制器:

galleryControllers.controller('ArtworkCtrl', ['$scope', '$routeParams', '$http', '$filter', function($scope, $routeParams, $http, $filter) {
    $scope.url = $routeParams.artworkUrl;
    $http.get('gallery.json').success(function(data) {
        // get genre from url
        $scope.artworks = $filter('filter')(data, {
            genre: $routeParams.artworkGenre
        });
        var artworks = $scope.artworks;

        // get item from url
        $scope.artwork = data.filter(function(entry) {
            return entry.url === $scope.url;
        })[0];
        var artwork = $scope.artwork;

        var url = $scope.url;
        //$scope.orderProp = 'year';

        // current artwork
        //$scope.currentArtwork = $scope.artworks[currentIndex];

        // the index of the selected artwork in the array.
        var currentIndex = $scope.artworks.indexOf($scope.artwork);

        $scope.prevArtwork = function(currentIndex) {
            var prevIndex = currentIndex - 1;
            if (prevIndex < 0) {
                // move over to the last index, if we already are at the start
                prevIndex = $scope.artworks.length - 1;
            }
            //console.log(artworks[prevIndex].url);
            return prevIndex;
        }

        $scope.nextArtwork = function(currentIndex) {
            var nextIndex = currentIndex + 1;
            if (nextIndex >= $scope.artworks.length) {
                // move over to start if we already were at the end of the list
                nextIndex = 0;
            }
            //console.log(artworks[nextIndex].url);
            return nextIndex;
        }
    });
}]);

最后我自己弄明白了,首先我用它来重新排序数组:

  artworks.sort(function (a, b) {
    return b.year.localeCompare(a.year);
  });

其次,我将控制器的 previous/next 部分更改为:

  /* previous button */
  if (currentIndex > 0)
    $scope.prevArtwork = Number(currentIndex) - 1;
  else
    $scope.prevArtwork = artworks.length - 1;

  /* next button */
  if (currentIndex < artworks.length - 1)
    $scope.nextArtwork = Number(currentIndex) + 1;
  else
    $scope.nextArtwork = 0;

然后像这样在模板中访问它:

{{artworks[prevArtwork].url}}

完美运行,没有任何骇人听闻的东西。