Simple Element Toggling With AngularJS


Toggling UI elements is a chore that nobody enjoys. Back when your web apps were primarily jQuery or raw JavaScript you would need to wire up an event handler, catch the click event, determine the current visibility state and switch it. A fairly small job, but still an annoying one when you have a page full of these elements.

With Angular you can accomplish this without writing any code, simply by using two HTML attributes.

Example, say I want to hide an input box, and have it appear when I click a button, then hide when I click it again.

<a ng-click="showInput = !showInput">Toggle Input</a>
<input type="text" ng-show="showInput" />

And that’s all there is to it.

The text input is only being shown when the $scope.showEmailInput variable evaluates to true, which of course it doesn’t because it doesn’t exist yet, so it is hidden.

Once you click the Toggle Email Input button it simply sets the $scope.showEmailInput variable to be the inverse of what it currently evaluates to which means it will now become true and the variable will actually exist on the scope now.

This is a super clean way to toggle the visibility of elements without requiring any plumbing code, events or variables to be manually configured on your scope.