showWhenState: Conditional Elements In Ionic by State Last update: 2015-03-24

showWhenState: Conditional Elements In Ionic by State

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.

showWhenState Usage

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.

<script src="lib/ionic.ion.showwhen.js"></script>

Next, import the module into your app module.

angular.module('myCoolApp', ['ionic','ionic.ion.showWhen'])

Finally, mark an element with the show-when-state attribute and the id of the state.

<div show-when-state="tabs.home">test</div>

This element will only show on the tabs.home state.

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.

.state('main.home', {
	url: '/home',
	views: {
		'main': {
			templateUrl: 'home.html',
			controller : 'HomePageController'

In this example, the id of the state would be main.home.

Match Multiple States

If you want an element to show up on multiple states, you can pass the directive multiple states separated by two pipes surrounded by spaces (the OR operator in javascript). For example, the following will display on either the tabs.about state or the tabs.facts state.

<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!

If you want more content like this, please check out My Blog or follow me on twitter (@andrewmcgivery)!