Skip to content

Instantly share code, notes, and snippets.

@jdstein1
Last active December 18, 2015 12:39
Show Gist options
  • Save jdstein1/5784357 to your computer and use it in GitHub Desktop.
Save jdstein1/5784357 to your computer and use it in GitHub Desktop.
Toggling with AngularJS

Toggling with AngularJS

by Jeff Stein

About

This is a small example of how you can toggle classes and overlays with the ngClick directive. It performs a show/hide on an overlay DIV, activates/deactivates clicked item, and changes the state of the overlay.

function AdminController($scope) {
// create data objects...
$scope.sections = [{
name: 'Clients'
}, {
name: 'Employees'
}, {
name: 'Others'
}];
$scope.fToggleSection = function (section) {
if ($scope.selected === section) {
$scope.selected = ''; // reset state of selected flag.
} else {
$scope.selected = section; // set state of selected flag to current item.
}
$scope.overlayFlag = false; // reset state of overlay flag.
};
$scope.isSelected = function (section) {
return $scope.selected === section; // return boolean.
};
$scope.fToggleOverlay = function () {
$scope.overlayFlag = !$scope.overlayFlag; // toggle state of overlay flag.
};
}
<html>
<head>
<title>Toggling with AngularJS</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body ng-app>
<div ng-controller="AdminController">
<ul class="list-holder">
<li ng-repeat="section in sections" ng-class="{active:isSelected(section)}">
<span ng-click="fToggleSection(section)">{{section.name}}</span>
</li>
</ul>
<p ng-click="fToggleOverlay()" ng-class="{true:'green',false:''}[overlayFlag]" ng-hide="isSelected('')" ng-show="!isSelected(section)" class="overlay">overlay for: {{selected.name}}</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<script src="controller.js"></script>
</body>
</html>
ul {background:lightblue;}
p, ul li {padding:0.25em;}
p {text-align:center;}
.overlay {
position:absolute;
top:0;
left:10%;
background:black;
color:white;
opacity:0.5;
width:90%;
height:100%;
}
.green {background:green;}
.active {background:yellow;}
@jdstein1
Copy link
Author

AngularJS is required...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment