CakePHP & AngularJS Pagination

It is actually pretty easy to make your RESTful calls in CakePHP paginateable by using what the Paginator Component already offers us and using Angular UI Bootstrap Paginator on the client side code. On our server side we just use the built in serialization of CakePHP to generate the response. This is an example of a CakePHP controller index() method that is paginateable:

Now let’s fetch the data via a custom Angular JS service in our Angular controller. The service “someApiService” is doing nothing more than a $http.get() call internally and resolving the result and then returning the promise again.

We also need a method to do the page change when one of the pagination links is clicked, so that a new request is done with the “page” param is issued. This is actually the reason we’ve wrapped the API call in a function, we don’t have to duplicate the code. You’ll call getData() one time to load the data when you enter the page and later each time a page button is clicked.

In your Angular view:

That’s all, as you can see it is pretty easy to get AJAX pagination working with these two awesome frameworks!

Loading static JSON data from the rendered page into AngularJS

In our scenario we didn’t wanted to build a whole single page application but instead needed to deal with data after the post was send to the server but didn’t save for some reason, so the page is rendered again and the data shown again as well. This caused the Angular controller to lose it’s set data.

I was looking for a way to prevent this and injecting any kind of data into my Angular app. I finally came up with a small directive that will read the json data, decode it and set it to a given scope variable.

This is the small directive that will load your data in your controllers scope:

In your applications code, in this case php, you can now do this:

If any one knows a better way to deal with this scenario I’m open for any suggestions and criticism!