Rails will_paginate gem with angular.js to do pagination
Asked Answered
L

2

1

Context: I have a Rails backend serving as an API to an Angular.JS front-end application.

Task: I want to retrieve all of the records of different species of "dinosaurs" from the Rails backend. Since there are over 500 records, I want to only get 30 species at a time.

My current approach: I am using the will_paginate gem in my Rails index controller action for the dinosaurs_controller. I have it running like this.

def index
  @dinosaurs = Dinosaur.paginate(:page => params[:page], :per_page => 30)
end

In my Angular code:

I have a module called DinoApp and am using ngresource to create an Entry resource

app = angular.module("DinoApp", ["ngResource"])

app.factory "Entry", ["$resource", ($resource) ->
  $resource("/api/v1/dinosaurs/:id", {id: "@id"}, {update: {method: "PUT"}} )
]

My Angular controller looks like this:

@MainController = ["$scope", "Entry", ($scope, Entry) ->
  $scope.entries = Entry.query({page: 1})
  $scope.viewPost = (dinosaurId) ->
]

This line of code would hit the API at dinosaurs_controller's index action and will only return 30 species of "dinosaurs" at a time:

$scope.entries = Entry.query({page: 1})

Now - how would I get angular.js to show a next page button and append the next page to the view?

Loera answered 8/10, 2013 at 18:24 Comment(3)
will you able to solve this ?Filmdom
Any chance of posting your complete solution using the angular-will-paginate gem?Fibre
no, i wasn't able to solve it but see heavysixer's directive below. hopefully he can post an exampleLoera
I
4

I created a directive for this, which might be helpful:

https://github.com/heavysixer/angular-will-paginate

Inkstand answered 17/12, 2013 at 19:53 Comment(3)
Thanks for the gem - I just ran into a couple of issues: config options for previous and next are actually required (not optional) and I had a little trouble getting the template to load from cache - it couldn't find the path - but I was able to get it to work and it saved me a bunch of time. Thanks!Afflictive
cool thanks for the feedback i'll look at the config object and make sure that the prev / next are truly optional.Inkstand
The gem looks good. Any chance of posting Rails / Angular example code using it?Fibre
F
1

You can use a counter for the number of pages that gets incremented each time your controller gets called.

var counter = 1;

$scope.loadPage = function() {
$scope.entries = Entry.query({page: counter})   
counter += 1 ;    
}

And have a button that refer to that next page.

<button ng-click="loadPage()">Next page</button>
Ferrocyanide answered 24/2, 2014 at 1:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.