Translate

Showing posts with label Symfony2. Show all posts
Showing posts with label Symfony2. Show all posts

Friday, June 5, 2015

AngularJs + Symfony2 Dealing with routes


This tutorial intends to explain how to integrate Symfony2 routes and angularJs routes in order to understand how they are going to  communicate.


Step1: First of all, we need to install a bundle called FOSJsRoutingBundle that will help us to access to the symfony2 route from javascript.

Actually,it's easy to install this is the GIT repository: FOSJsRoutingBundle
And this is installation Method : How to install FOSJsRoutingBundle


Step2: Configure our symfony2 routes.We need to create our routes to access  specific actions or method.

in the file: src/REVC/BlogBundle/Resources/config/routing.yml
  

rou_dispacher:
    path:     /dispath/{template}
    defaults: { _controller: REVCBlogBundle:Default:dispatch }
    options:
        expose: true



Because we are using the bundle FOSJsRoutingBundle, we need to expose our route.To avoid creating routes for each action,I've designed this route to receive a parameter which is the template name.


Step3: Create our controller for the route created.

in the file: src/REVC/BlogBundle/controller/ArticleController.php
  

       public function dispatchAction($template)
        {
            return $this->render('REVCBundle:'.$template);
        }

  

Having that controller, you will be able to access to any  template you want.


Of course, don't forget to  create yours template in :src/REVC/BlogBundle/Resources/views/Article

Step4: Finally, we need to create our AngularJs route:

I have created my angular files in : src/REVC/BlogBundle/Resources/public/js/app.js

 app.config(['$routeProvider',function($routeProvider){

        $routeProvider
                .when('/home',{ 
                           templateUrl: Routing.generate('rou_dispacher',{template:"Article:home.html.twig"})
               })
                .when('/',{
                           templateUrl: Routing.generate('rou_dispacher',{template:"Article:home.html.twig"})
               })
                .when('/edit',{
                           templateUrl: Routing.generate('rou_dispacher',{template:"Article:edit.html.twig"}) 
                })
                .when('/create',{
                           templateUrl: Routing.generate('rou_dispacher',{template:"Article:create.html.twig"}) 
                });
 
    }]);



As you can see , I have used the functions called Routing.generate that allows us to communicate with the symfony2 route.

Basically, the Routing.generate will accept the following parameters:

Routing.generate('route_name',{variable});

Having that configuration, it will be easy to work with AngularJs and Symfony2.

This is the screen shot  about the structure folder of my application.