Play Framework 2.1 - AngularJS routing - best solution?

Dominic Bou-Samra picture Dominic Bou-Samra · Apr 18, 2013 · Viewed 13.5k times · Source

I am working my way through the AngularJS tutorial. Angular uses it's own JS routing mechanism to allow for single page apps. A sample routing file for Angular looks like this:

angular.module('phonecat', []).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
      when('/phones', {templateUrl: '/partials/phone-list',   controller: PhoneListCtrl}).
      when('/phones/:phoneId', {templateUrl: 'partials/phone-detail', controller: PhoneDetailCtrl}).
      otherwise({redirectTo: '/phones'});
}]);

I am trying to come up with a good place to store my partials (Angular specific HTML files). Ideally i WOULD like the ability to template them from within Play (i.e. have them as *.scala.html files). I can accomplish this using a a Play routes file like so:

GET     /partials/phone_index       controllers.Application.phone_index

I basically partials/ to a controller action like this:

def phone_index = Action {
  Ok(views.html.partials.phone_index())
}

The solution I am looking for is a combination of two ideals:

  1. I would have some sort of mapping that lets me visit any file under /partial/* and get back the partial file.
  2. I would like the overriding a route to a specific partial so I CAN use a controller action to dynamically fill with data (rare).

Any ideas?

Answer

Pere Villega picture Pere Villega · Apr 22, 2013

When I was trying something similar I came to the conclusion that it's better to break it on 2 parts:

  • Use Play as a backend you interact with via Ajax calls
  • Store the Angular templates in Play public folder (something like /public/angular/) and use the default AngularJs way to map the templates

I know it doesn't sound great and really doesn't answer your question on how to do it, but trying to link both frameworks may be problematic due to the way templates and their urls are mapped in Angular, and the benefit will be very small as any change will imply a lot of work, thus removing the arguably main benefit of both Play and Angular, rapid development.

This also allows you to separate concerns better, which if your project grows may be important as you can just take the AngularJS code away as a standalone app connecting to a backend, and it will work fine.

You can see some sample code of what I said (based on the TODO tutorial of AngularJS) in this Github repository. I warn you, the code is not too nice, but should give you an idea and as a bonus shows you how to integrate Jasmine into Play, for AngularJS unit testing.