When inside a route, you can use the controller to transition to another route. We'll look at an example on how to transition from one route to another.
$ ember g route foo1 $ ember g route foo2 $ ember g controller foo1 $ ember g controller foo2 $ ember g template index
This will generate two different routes for us—the foo1
and foo2
routes. Each route will have a button that transitions to the other route. Each controller will handle the action logic.
// app/controllers/foo1.js import Ember from 'ember'; export default Ember.Controller.extend({ actions: { enter(){ this.transitionToRoute('foo2'); } } });
This controller has one action called enter
that transitions to the route called foo2
. The this.transitionToRoute
method is used to transition to different routes in the application. It takes two arguments. The first argument is the name of the route. The second argument is optional, and it is where you enter in the model. By default, it will be serialized in the URL if added.
The trasintionToRoute
method can take route paths as well. For example, you might have a foo2
nested route called foo3
. You can transition to this route by calling this.trasitionToRoute('foo2.foo3')
.
// app/controllers/foo2.js import Ember from 'ember'; export default Ember.Controller.extend({ actions: { enter(){ this.transitionToRoute('foo1'); } } });
When the enter
action is triggered, it transitions to the foo1
route.
// app/templates/foo1.hbs This is Foo1<br> <button {{action 'enter'}}>Move to route foo2</button>
This button
triggers the enter
action
in the foo1
controller.
// app/templates/foo2.hbs This is Foo2<br> <button {{action 'enter'}}>Move to route foo1</button>
This button
triggers the enter
action
in the foo2
controller.
// app/templates/index.hbs {{link-to 'Foo1 Route' 'foo1'}}<br> {{link-to 'Foo2 Route' 'foo2'}}<br>
This uses the link-to
helper in a non-block form. The first argument is the name displayed and the second is the name of the route.
// app/templates/application.hbs {{#link-to 'application'}}<h2 id="title">Welcome to Ember</h2>{{/link-to}} {{outlet}}
The application template file has a link back to the application at the top.
ember server
and you'll see the following screen after opening a web browser:This displays the foo1 route.
After the button is clicked, the foo2 route is displayed.