How to access model using controllers


#1

How to access model data using controllers. Without using route.


#2

Not sure if I got you right, but did you try to call this.model() in the controller? Is it a suitable solution?


#3

Models are set on controllers by routes. No route, no model.

If you want to access the store from a controller, you can call this.store from its methods. More often than that though, you would inject a service into your controller that does your data access for you. Here’s the relevant guide.

EDIT: The store is already injected into controllers by default. You should still use services to access data.


#4

I don’t know for now why do I think so, but I was sure that in some conditions Ember would generate a default route with the model function, where it’s trying to obtain the data for the resource of the same name as the route. Is it a fantasy?


#5

Routes have a model hook that fires when you enter them that is typically used to retrieve data. In the route’s setupController hook, this model gets set on the controller’s model property. In ObjectControllers and ArrayControllers, you can access the model’s properties as if they were properties of the controller. This confused a lot of people, which is why those classes are deprecated.

If you need to look up raw model data from a controller directly you can, but there are few/no good reasons for doing so. If it’s not part of the route’s model, it’s generally better represented as a service or encapsulated in a component.


#6

In fact I know it all, but nevertheless thanks for your clarification.


#7

Thanks for the ideas and pointers.