Controllers in Ember 2
Published on Aug 03, 2016
Controllers aren't dead yet- they're only mostly dead.
This episodes shows 3 ways that controllers have been replaced in Ember 2.x, and 1 way that they're still the same.
Ember 2 has been out for a while, but I get still quite a few questions about what to do with controllers. What is their role in Ember 2? Are controllers dead like some people have said? Well, they’re not dead yet. They’re only mostly dead. In this episode we’re going to go over four different things that controllers did in Ember 1.x and talk about how those things are accomplished in Ember 2.x.
The first of these is Rendering Partials with State. So in Ember 1.x you’d render something, and this would be a controller and you’d feed in a model. In Ember 2.x, that functionality has been replaced with components, and the components are much more flexible because you can feed in basically not just the model but several other attributes as well.
Then there’s the State in Each Loops. In Ember 1.x we had the
itemController, so in an
eachLoop you specify the
itemControllerName and then you can add properties to the things you’re looping through, things that wouldn’t necessarily fit on a model. In Ember 2.x, then we can just put a component within that loop and so we don’t have to have a separate
itemController. And we could’ve had a
blockComponent here as well.
Then there’s Global State. So in Ember 1.x we would create a controller to hold our
state, and then we would use
needs, or previously
controllerFor, and then we would call
controllers. controller name, and then we could get to the actual state that we were looking for. In Ember 2.x, that functionality as well as several others are taken care of by services. And you do that by injecting the service, and then you can just call the service as if it’s on the controller, no need to prefix it with services.something.
Finally there’s Actions and State for a Route. In Ember 1.x we would have our
actions and our
state on the
controller. In Ember 2.x, we do the exact same thing. In the future we’ll have routable components which will finally put the nail in the coffin for controllers, but those aren’t here yet.
So we went over four different uses of controllers in Ember 1.x, only one of which still requires a controller in Ember 2.x. So if you’re still using controllers for storing
state on a route, that’s fine, don’t worry about it. If you’re still using controllers for the other ones, it’s time to upgrade to Ember 2.