angularjssymfonyangular-ui-routerangular-ui-router-extras

Angularjs and dynamic routes


I am trying to create a link in my template angularjs by doing something like:

 <a ng-href="/#!/content/[[value.id]]">[[key]]</a>

But I am wondering myself if is possible do something like symfony2 does, example:

routing.yml

  home_redirect:
    path: /
    defaults:
        _controller: FrontendBundle:Controller:function
        path: /home
        permanent: true
    options:
        expose: true

And using it in your twig template by doing:

<a href="{{ path('home_redirect')}}"> one link to home </a>

That is really, really helpful because I don't have to "hardcode" all my routes.


Solution

  • To ensure a proper routing, you can use ui-router.

    Here is an exemple on plunker

    How this works :

    1 - Follow the installation guide on their github

    2 - Write your state definition :

    app.config(function($stateProvider, $urlRouterProvider){
      //If no route match, you'll go to /index
      $urlRouterProvider.otherwise('/index');
    
      //my index state
      $stateProvider
      .state('index', {
        url: '/index',
        templateUrl: 'index2.html',
        controller: 'IndexCtrl'
      })
    
      //the variable state depending on an url element
      .state('hello', {
        //you will be able to get name with $stateParams.name
        url: '/hello/:name',
        templateUrl: 'hello.html',
        controller: 'HelloCtrl'
      })  
    });  
    

    3 - Write links by their state name :

    //add this directive to an html element
    //This will go to /index
    ui-sref="index"
    //This will go to /hello/
    ui-sref="hello"
    //This will go to /hello/ben
    ui-sref="hello({name:'ben'})"
    //This will go to /hello/{myname}
    ui-sref="hello({name:myname})"
    

    4 - Get the param into your controller :

    //inject $stateParams
    app.controller('HelloCtrl', function($scope, $stateParams){
      $scope.controller = "IndexCtrl";
      //get the param name like this
      $scope.name = $stateParams.name;
    });
    

    Hope it helped. Also keep in mind the ui-router got some really powerful tools such as resolve and nested state/view. You'll probably need theses now or later.

    PS : If the plunker don't work, just fork it and save again.