Useful tricks for Ember Controllers
computed gives access to different included Ember functions for presenting or manipulating info provided by the router. A simple example:
It also lets you
map results to narrow them down or manipulate large amounts at once.
A simpler option for filtering is the
filterBy option, which doesn’t take a function. It simply takes three properties:
- The array to filter
- The property of each item in the array to check for the filter
- The value each selected property needs to be included. Otherwise it gets filtered out.
If you need to return a basic property of another object, you can use the
To input an array of items from an object for a computed property, you can use
There’s several other useful functions that can be imported from
@ember/object/computed for fast, computed values in controllers.
andfor doing a logical “and” comparison, that returns true if both values also return true
boolfor returning the dependent boolean of a variable
collectfor returning the values of other dependent properties (ie an array of values from other computed properties)
notEmptyfor if a value is null or a type of empty value, like an empty string (or the opposite with
ltefor doing basic greater than and less than calculations, with possible equal to’s too
interectfor, when using 2+ arrays as args, returning an array of all values they have in common
minfor calculating the max or min values in an array
notfor checking if a boolean argument is false (if the variable is
false, it returns
orfor doing a logical “or” comparison, that returns true if one value returns true
sortfor organizing an array in descending or ascending order based on one of the properties
sumfor adding up all the values in an array
uniqfor getting all the unique values in one or more arrays
uniqByfor arrays of objects, determining uniqueness by a specific key
This is a controller tool to move to different routes after an action. For example, you could have this activate on an “edit” screen to go back to the related “show” screen. Don’t forget to pass any needed parameters!
Another good use case: after deleting an item, go to the page with the list of remaining items.
In controllers, you can use Ember’s
toggleProperty method to quickly change a boolean value to its opposite. It works for both controller or Ember object values, like so:
Using Properties and Actions from other Controllers
For child or parent controllers, you need to
inject them into the controller. Then you access them through the namespace you select.