The main risk for an application using both symfony and angularjs is the duplication of 

information.

Both frameworks have their own methods to handle routing. We want to discuss how 

communication and sharing of routes can be allowed.

Angularjs handles routes on client side. As a default, angularjs makes use of `#!` in its routes. 

This behavior can be changed using the `html5mode` option. As a rule, this procedure is not 

advisable.

Imagine you have a symfony page where you need to use an angularjs module. The best way 

to handle routing is to let symfony manage page links, then angularjs routing can be configured 

like this:

myApp.config([
        "$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) {
          return $routeProvider.when("/form", {
            templateUrl: "/custom/templates/myform.html",
            controller: "myApp.FormController"
          }).otherwise({
            redirectTo: "form"
          });
        }
      ]);

So, once reached the involved page, angularjs will take care of routing.

Things to remember: if there are links not related to angularjs application within the element 

defining the app, always be sure to add `href="javascript:void(0)"`, otherwise angularjs routing 

will always be applied. 

Now let's consider the case you need to perform redirects or to use routes from symfony 

application in your angularjs script. 

How avoiding to rewrite the entire link?

For the purpose two bundles can be used: FOSJsRoutingBundle and 

CypressAngularNgRoutingBundle, "A Symfony2 bundle to expose your routing in Angular.js 

resource format".

This latter bundle allows to expose your routes using their simple name, centralizing their 

configuration and leaving their handling only to symfony side. 

Once installed the bundle, the global namespace makes available the NgRouting object, 

containing the generateResourceUrl method for generating a route from its name.

Alessandro Nuzzo

Senior Web Developer , Website , Git home page , @aleinside , Linkedin profile
I am a developer since 2006. I am a basket and whisky lover, interests that i follow separately for obvious reasons. I am also the Milan PHP User Group founder and coordinator.

All articles by Alessandro Nuzzo

Comments

comments powered by Disqus

cloudparty

Follow Us