我有一个Rails应用程序,并且公开了一个由Angular前端使用的API。我正在使用 will-paginate gem 分页我的大数据集。 gem需要通过参数传递:page 。
页面上的按钮工作正常,并调用 nextPage 或 prevPage 函数,但由于某种原因,params 页码不会传递给Rails控制器。
当用户按下下一个或上一个按钮时,我希望从rails控制器传送数据并在屏幕上刷新。
相关问题:Rails will_paginate gem with angular.js to do pagination
应用/控制器/ API / data_sources_controller.rb
class Api::DataSourcesController < Api::BaseController
def index
Rails.logger.debug("index: datasources, page: #{params[:page]}")
render json: Cosmic.paginate(:page => params[:page], :per_page => 50)
end
end
应用/资产/ Javascript角/控制器/ DatasetController.js.coffee
angular.module('assaypipelineApp').controller "DatasetController", ($scope, $routeParams, $location, DataSet) ->
$scope.currentPage = 1
$scope.init = ->
@panel_id = $routeParams.panel_id
console.log("dataset init: #{@panel_id}")
@datasetsService = new DataSet(serverErrorHandler)
$scope.datasets = @datasetsService.all({page: $scope.currentPage})
# pagination
$scope.prevPage = ->
console.log("prev #{$scope.currentPage}")
$scope.currentPage-- if $scope.currentPage > 0
$scope.datasets = @datasetsService.all({page: $scope.currentPage})
$scope.nextPage = ->
console.log('next')
$scope.currentPage++
$scope.datasets = @datasetsService.all({page: $scope.currentPage})
应用/资产/ Javascript角/服务/ DataSetService.js.coffee
angular.module('assaypipelineApp').factory 'DataSet', ($resource, $http) ->
class DataSet
constructor: (errorHandler) ->
console.log('dataset constructor')
@service = $resource('/api/data_sources/:id',
{id: '@id'},
{update: {method: 'PATCH'}})
@errorHandler = errorHandler
# Fix needed for the PATCH method to use application/json content type.
defaults = $http.defaults.headers
defaults.patch = defaults.patch || {}
defaults.patch['Content-Type'] = 'application/json'
all: ->
@service.query((-> null), @errorHandler)
find: (id, successHandler) ->
@service.get(id: id, ((data_set)->
successHandler?(data_set)
data_set),
@errorHandler)
在视图中
<ul class="pagination pull-right">
page {{currentPage}}
<li ng-class="{disabled: currentPage == 0}">
<a href ng-click="prevPage()">« Prev</a>
</li>
<li ng-repeat="n in range(pagedItems.length)"
ng-class="{active: n == currentPage}"
ng-click="setPage()">
<a href ng-bind="n + 1">1</a>
</li>
<li ng-class="{disabled: currentPage == pagedItems.length - 1}">
<a href ng-click="nextPage()">Next »</a>
</li>
</ul>
答案 0 :(得分:4)
在本书的帮助下,我解决了它:https://leanpub.com/angularails
答案其实很简单。
# pagination
$scope.setPage = (newPage) ->
newPage = 1 if newPage < 1
$scope.currentPage = newPage
$scope.getPage()
$scope.getPage = () ->
http =
method: "GET"
url: "/api/data_sources"
params:
page: $scope.currentPage
$http(http)
.success (response) ->
console.log(response)
$scope.datasets = response