Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the URL when paging using UI Router?

I have an Angular JS project using Angular UI-Router which is going great but I am trying to implement the UI Bootstrap pagination directive and can't work out the correct strategy.

I have a table of data shown 1 page at a time and I have the pagination directive in place showing the correct number of page links. When you click a link it gets the new page number and makes a Restangular call to the api to get the new records and binds them to the table.

That's all working well, but obviously when you page through the data the URL doesn't change so the user can't use the browser back/forward buttons to navigate their history. Ideally I would like to use the following URLs:

/contacts
/contacts/page-2
/contacts/page-3

I would also like to include sorting in the URL but that's another question.

I could achieve this but by manually transitioning to a new state when one of the pagination buttons is clicked, but that would reload the controller and all of it's contents, making additional ajax calls to the server and making ugly flashes of un-styled content as it recreated the pagination control etc.

Ideally I would be able to change the URL and add a history state but without triggering an actual state change and reloading/running the controller for that view. I'm not sure if this is even possible, let alone how to do it.

Anybody got any ideas?

like image 405
jonhobbs Avatar asked Mar 10 '14 01:03

jonhobbs


1 Answers

This is easily achievable with $stateParams

For example

$stateProvider
.state('contacts',{
 url: '/contacts',
 templateUrl: 'contacts.html'
}).state('contacts.paginated', {
    url: "/contacts/page-:pageNum",
    templateUrl: 'contacts.html',
    controller: function ($stateParams) {
        // If we got here from a url of /contacts/page-2
        expect($stateParams).toBe({pageNum: 2});
    }
})

I would choose a different pagination scheme however Either /contacts/page/1 or /contacts?page=1 both are easily achievable with ui-router

like image 56
Vlad Gurovich Avatar answered Nov 03 '22 19:11

Vlad Gurovich