How to access dynamic segment in a controller in ember.js?

by wilmer.lemke , in category: Javascript , 4 months ago

How to access dynamic segment in a controller in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , a month ago

@wilmer.lemke 

To access dynamic segments in a controller in Ember.js, you can use the params property in the Route object. Here's an example:

  1. Define a dynamic segment in your router configuration:
1
2
3
Router.map(function() {
  this.route('post', { path: '/post/:post_id' });
});


  1. Define a route for the dynamic segment:
1
2
3
4
5
6
7
import Route from '@ember/routing/route';

export default Route.extend({
  model(params) {
    return this.store.findRecord('post', params.post_id);
  }
});


  1. Now, in your controller, you can access the dynamic segment value using the params property like this:
1
2
3
4
5
6
7
8
9
import Controller from '@ember/controller';

export default Controller.extend({
  queryParams: ['post_id'],
  
  post_id: Ember.computed('model', function() {
    return this.get('model.post_id');
  })
});


In this example, we are accessing the post_id dynamic segment value in the controller and storing it in the post_id property. You can then use this property to perform any necessary logic or actions based on the dynamic segment value.