What You’ll Learn
How to create a smooth slide-in menu using ngAnimate
Using ng-class
for toggling menu visibility
Applying CSS transitions for animations
Enhancing the menu with click events
1️⃣ Setting Up ngAnimate
To enable animations in AngularJS, you need to include ngAnimate
.
Step 1: Include AngularJS and ngAnimate
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-animate.min.js"></script>
Step 2: Create an AngularJS App
var app = angular.module('myApp', ['ngAnimate']);
2️⃣ Creating the Slide-In Menu UI
The menu will slide in from the left when a button is clicked.
HTML Code
<style>
/* Container for the menu */
.menu-container {
position: fixed;
top: 0;
left: -250px; /* Initially hidden */
width: 250px;
height: 100vh;
background-color: #333;
color: white;
transition: left 0.4s ease-in-out;
padding: 20px;
}
/* Menu visible state */
.menu-container.open {
left: 0;
}
/* Close button */
.close-btn {
cursor: pointer;
background-color: red;
color: white;
border: none;
padding: 10px;
margin-bottom: 10px;
width: 100%;
text-align: center;
}
/* Open menu button */
.menu-btn {
position: fixed;
top: 20px;
left: 20px;
background-color: dodgerblue;
color: white;
border: none;
padding: 10px;
cursor: pointer;
}
</style>
<div ng-app="myApp" ng-controller="MenuCtrl">
<!-- Button to open the menu -->
<button class="menu-btn" ng-click="toggleMenu()">☰ Open Menu</button>
<!-- Slide-in Menu -->
<div class="menu-container" ng-class="{'open': isMenuOpen}">
<button class="close-btn" ng-click="toggleMenu()">Close Menu</button>
<h2>Slide-In Menu</h2>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</div>
3️⃣ Adding AngularJS Functionality
Now, we create a controller to handle menu toggling.
JavaScript Code
app.controller('MenuCtrl', function ($scope) {
$scope.isMenuOpen = false;
$scope.toggleMenu = function () {
$scope.isMenuOpen = !$scope.isMenuOpen;
};
});
4️⃣ How It Works
✔ The menu starts hidden (left: -250px
).
✔ Clicking the Open Menu button adds the open
class, making left: 0
.
✔ Clicking the Close Menu button removes the open
class, sliding the menu out.
✔ ng-class
dynamically toggles the open
class based on $scope.isMenuOpen
.
5️⃣ Enhancements: Closing Menu on Click Outside
To close the menu when clicking outside, use $document
.
Updated JavaScript Code
app.controller('MenuCtrl', function ($scope, $document) {
$scope.isMenuOpen = false;
$scope.toggleMenu = function () {
$scope.isMenuOpen = !$scope.isMenuOpen;
};
// Close menu when clicking outside
$document.on('click', function (event) {
if (!$scope.isMenuOpen) return;
var menu = document.querySelector('.menu-container');
if (!menu.contains(event.target)) {
$scope.$apply(function () {
$scope.isMenuOpen = false;
});
}
});
});
Now, clicking outside the menu will close it! 🎯