dombruno.com

Mobile slide menu with AngularJS and CSS3

demo | download code

about

This is a quick tutorial on how to do a mobile slide menu with AngularJS and CSS3. I'm using Angular 1.2 with Angular touch. Using Angular touch will remove the 300ms delay all mobile browsers add to click events and will let us add a finger swipe event to close the menu.

Note: I don't show all of the code in this tutorial, make sure to reference the source code above for all of the code

html

Make sure you have these libraries included in your code, and a controller function wrapping your entire app.


<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.0rc1/angular-route.min.js"></script>
<script src="http://code.angularjs.org/1.2.0rc1/angular-touch.min.js"></script>

Below is the html code for your app. The entire app works on the variable "showmenu". The toggleMenu() function will set this variable to true or false. Based on this value the menu will show or not.


<div id="menuleft" ng-class="{hide:!showmenu,slide:showmenu}">
<h1>Demo</h1>
<ul>
<li><a ng-click="toggleMenu()">Link 1</a></li>
</ul>
</div>
</div>

<div id="all" ng-class="{hide:showmenu,slide:!showmenu}">
<div class="overlay" ng-class="{show:showmenu}" ng-swipe-left="showmenu=false"></div>
<div id="header">
<button ng-click="toggleMenu()"></button>
<h1>Demo</h1>
</div>

<div id="wrapper">
</div>
</div>

css

CSS3 transitions will create the 'slide' effect on the menu (and page).


#menuleft.slide{left:0}
#all.hide{position:fixed;left:50%;top:0;width:100%}
#all.slide{position:relative;}
.slide,.hide{transition: all 0.2s ease;}

javascript

Create a function that will toggle showmenu to true or false


var app = angular.module('myApp', ['ngRoute','ngTouch']);
app.controller("AppController", function($scope){

//default the menu to not show
$scope.showmenu=false;

//this is the toggle function
$scope.toggleMenu = function(){
$scope.showmenu=($scope.showmenu) ? false : true;
}

});

Finally here is the swipe directive. This controls the 'swipe' effect that allows users to close the menu by swiping a finger over the overlay.



app.directive('mySlideController', ['$swipe',
function($swipe) {
return {
restrict: 'EA',
link: function(scope, ele, attrs, ctrl) {
var startX, pointX;
$swipe.bind(ele, {
'start': function(coords) {
startX = coords.x;
pointX = coords.y;
},
'move': function(coords) {
var delta = coords.x - pointX;
// ...
},
'end': function(coords) {
// ...
},
'cancel': function(coords) {
// ...
}
});
}
}
}]);

the end

Hopefully this tutorial was helpful and will help you build good AngularJs apps
Follow me for more @dombruno