A while back I released an Ionic Ion called ionic-ion-showWhen with the purpose of showing or hiding an element based on the size of the screen.
That directive has now been expanded to include
hideWhen (the reverse) and the brand new
showWhenState. This post will talk about what this new directive does and how to use it in your app.
What does it do?
showWhenState displays an element if the current state matches the state passed to the directive. You can also have it match multiple states (via OR logic) allowing an element to be displayed if one of multiple states are matched.
When referring to state, we are talking about the state as defined by the ui-router that comes out of the box with Ionic. Think of each state as a view or page in your app.
To use the directive, first grab the
ionic-ion-showWhen module off of GitHub. Import the script into your index.html page somewhere after the Ionic scripts.
Next, import the module into your app module.
Finally, mark an element with the
show-when-state attribute and the id of the state.
This element will only show on the
The state id refers to the name given to the state in your state’s configuration. For example in the following state configuration, the first parameter passed to
.state() is the id.
controller : 'HomePageController'
In this example, the id of the state would be
Match Multiple States
tabs.about state or the
<div show-when-state="tabs.about || tabs.facts">test</div>
The use case for this directive is you have part of the layout of your app that doesn’t change (for example a side menu, tabs, or nav bar) but you want the content within it to show based on state. One specific use case for this would be having different buttons on the right side of a nav bar depending on which state you are on.
Using the showWhenState directive is super easy and can help abstract away one of those many things you may be tempted to do in your controller. Feel free to use it in your apps!
Get the free 7 day Ionic Crash Course to learn how to:
- Get started with Ionic
- Build a Tab Bar navigation
- Make HTTP calls to a REST API
- Store Data inside your app
- Use Cordova plugins
- Style your Ionic app
The course is free, so there's nothing you can lose!