Neil Young
Neil Young

Reputation: 556

Localised AngularJS Routes

I have been coding BackboneJS and have successfully built large projects using BackboneJS and AMD.

I am now looking into using AngularJS and have got an implementation with AMD and have built some controllers and services so pretty comfortable so far.

Only thing is that we build a lot of applications that need to be localised for different territories. Because of this I have successfully configured Angular Translate and it works fine.

What Angular Translate does not support is the creation of localised url routing which is something I was able to achieve easily in BackboneJS by dynamically updating the routes object.

Can anyone point me in the right direction for an article or post on how to do this with AngularJS. Been trawling through Google but cannot seem to find anything!

Upvotes: 2

Views: 197

Answers (1)

Ahmed Nuaman
Ahmed Nuaman

Reputation: 13211

So, whether or not this is the best solution for you I'll explain an approach we took when it came to having a dumb Angular app that required routes be defined on the backend. So at run time the URL that the user comes in on is unknown to our app, what we do is the following:

  • Call a service that defines our app URLs
  • Validate the retrieved URLs
  • Call $route.reload() to essentially restart (it doesn't actually restart the application, but just runs the route parser again) the application

We then defined routes based on the app's features, eg: http://foo.bar/product/:slug. So if a user came in on http://foo.bar/product/foobar the app at run time has no idea whether or not foobar exists. This allowed us to keep the UI dumb and define the routes on the backend; therefore...

  1. In your routes config set up base routes, eg /product/:slug, /page/:slug, etc...
  2. Create a factory that keeps a boolean variable which is whether or not the app has loaded the localisation data; if it's false then your product, page, etc... controllers will just silently stop at their init
  3. In your base controller load your localisation data, validate it, etc... Once you're happy you then run $route.reload() and this time set the factory flag to true
  4. Your product, page, etc... controllers will get called again, but the factory flag will be true, then they can now refer to your loaded localisation data
  5. Profit

Hopefully it doesn't sound painful, it can be an elegant solution and works really well. Just make sure you have a nice polite loader.

Upvotes: 1

Related Questions