How to create controller with own model without route in ember.js?

by cali_green , in category: Javascript , 4 months ago

How to create controller with own model without route in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , a month ago

@cali_green 

In Ember.js, the controller is typically associated with a route and its corresponding model. However, if you want to create a controller with its own model without a route, you can do so by using a service.


Here's how you can create a controller with its own model without a route in Ember.js:

  1. Create a service: First, create a service to hold the model data. You can generate a service using the Ember CLI by running the following command:
1
ember generate service my-service


This will create a new service file in the app/services directory.

  1. Add the model data to the service: Now, you can add the model data to the service. For example, you can define a property myModel in the service and set it to some initial data. Here's an example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// app/services/my-service.js

import Service from '@ember/service';

export default class MyServiceService extends Service {
  myModel = {
    name: 'John Doe',
    age: 30,
    email: '[email protected]'
  };
}


  1. Create a controller: Next, you can create a controller that injects the service and uses the model data from the service. You can generate a controller using the Ember CLI by running the following command:
1
ember generate controller my-controller


This will create a new controller file in the app/controllers directory.

  1. Inject the service into the controller: In the controller file, inject the service using the @service decorator and access the model data from the service. Here's an example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// app/controllers/my-controller.js

import Controller from '@ember/controller';
import { inject as service } from '@ember/service';

export default class MyControllerController extends Controller {
  @service myService;

  get myModel() {
    return this.myService.myModel;
  }
}


  1. Use the controller in a template: You can now use the controller in a template to render the model data. For example, you can create a template file my-controller.hbs in the app/templates directory and use the myModel property from the controller to display the model data. Here's an example template:
1
2
3
4
5
<!-- app/templates/my-controller.hbs -->

<h1>{{myModel.name}}</h1>
<p>Age: {{myModel.age}}</p>
<p>Email: {{myModel.email}}</p>


That's it! You have now created a controller with its own model without a route in Ember.js using a service.