[AngularJS] Toggle Element without JavaScript


The power of AngularJS is best described by toggling element without writing any JavaScript code. This example will show you how to do toggle-able effect in AngularJS way.

Please first see:

Demo

The source code of above demo:

ngtoggle.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>AngularJS Toggle Element without JavaScript - Demo</title>
</head>
<body ng-app>

<a href="javascript:void(0);" ng-init="isShow = false" ng-click="isShow = !isShow">
  <span ng-show="isShow">&#9660;</span>
  <span ng-hide="isShow">&#9658;</span>
  <span>click me to toggle</span>
</a>
<div ng-show="isShow" style="width: 300px; height: 300px; background-color: yellow">
  content
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
</body>
</html>

As you can see from the source code, we use a variable isShow and built-in directives ng-init, ng-click, ng-show, and ng-hide to achieve toggle-able effect. The beauty of this solution is that you do not need to write any JavaScript code, and the code is easily readable and understandable at the same time!