EmberJS-Router Dynamic Segment



Description

A dynamic segment begins with a : in route() method and it is followed by an identifier. In your model an URL must be defined with an id property.

Syntax

Router.map(function() {
   this.route('linkpage', { path: '/linkpage/:identifier' });
});

Example

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Dynamic Segment Router</title>
      <!-- CDN's -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
      <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script>
      <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script>
      <script src="https://builds.emberjs.com/release/ember.debug.js"></script>
      <script src="https://builds.emberjs.com/beta/ember-data.js"></script>
   </head>
   <body>
      <script type="text/x-handlebars" data-template-name="index">
         <!-- refers to the 'getIds' action -->
         <a href="#" {{action "getIds"}}>Click To Get IDs Of Student</a>
      </script>

      <script type="text/x-handlebars" data-template-name="posts">
         <!-- getting the student Ids -->
         <b>Student Id:</b><i>{{stud_id}}</i><br/>
         <b>Student Name:</b>
         <i>{{info_id}}</i>
      <script>

      <script type="text/javascript">
         App = Ember.Application.create({});

         App.Router.map(function(){
            //definig the route
            this.route('posts', { path: 'school/:stud_id/:info_id'});
         });

         App.IndexController = Ember.Controller.extend({
            actions:{
               getIds: function() {
                  //this passes the ID's other than loaded object
                  this.transitionToRoute('posts', { stud_id: 1, info_id: "Micky" });
               }
            }
         });

         App.IndexRoute = Ember.Route.extend({
            //model() method is called with the params from the URL
            model: function(params) {
               return params;
            }
         });
      </script>
   </body>
</html>

Output

Let's carry out the following steps to see how above code works:

  • Save above code in routing_dynmc_segt.htm file

  • Open this HTML file in a browser.

Advertisements