Series: Tables of Data

query params

Published on Mar 21, 2015

We use query-params so that we can track controller state between sessions. We're also able to simplify some code. More features, less code- how awesome is that!




In the last three videos, we created a nice intuitive UI for sorting our videos. However, there was still one problem: when you reload the page, it resets your sorting. That also means that when you give someone the url for this, they’ll see a different sorting than you meant them to see.

Query params can fix it! Just tell the controller what query params you want to use. Note that the query params must be properties on the controller. When we change the sort, it saves it in the url! Notice that if we make it sort by the default, that parameter disappears. Pretty nice, right? And it was only one line of code. Let’s look at that diff. Wow, yea, that’s all. Query params are powerful, and they’re crazy easy. But there are also some more advanced features, and I’m going to show you one of those.

Query params changes the URL, so as you might guess, you can change query params using the link-to helper. Currently we’re changing the params with this action. But if we use links, we can eliminate it. And we can eliminate passing in the action. And we can eliminate this action as well. Now we just have to turn these two action calls into links.

Let’s look at the anatomy of a basic link-to helper. You have the surrounding link-to signifier, and then you have the name of the route you’re linking to, and then you have the content that the link text. A common variation is to pass in an item or an id, for example if you wanted to go to show a specific video. To use query params in link-to, we use a subexpression helper in parentheses. It starts by naming the helper, query-params, and then passing in values.

Let’s do that, and pass in sortAscending and sortproperties. sortAscending is the true or false boolean, based on which arrow it is, while sortProperties will be an array that we form from the sortProperty we passed in to the component. And you’ll see that it still works, just like before… but now with much more elegant code.

You can see that the query-params API is both powerful and easy to use. There are many more advanced features that we didn’t get to today. If you’re curious, you can look them up in the ember guides.

Next week, we’ll use what we’ve learned here to add pagination. See you then!

Tables of Data

Subscribe to our mailing list