So, I'm reading one of the best StackOverflow answers ever given on AngularJS. Josh David Miller had an excellent answer that has become quite popular.
Being quite the AngularJS novice, I picked up quite a bit from his answer. The most important tidbit for me was "5. Conceptually, directives are not packaged jQuery". In my Phonegap / Topcoat / AngularJS App Template, I was NOT using jQuery. In fact, I was being "clever" and using pure HTML5 DOM manipulation techniques to add a class to the app container to cause it to slide in and out.
link: function( scope, element, attrs, controller ) {
scope.toggleMenu = function() {
var appContainer = document.getElementById('main-app');
if ( appContainer.classList.contains('slide-in') ) {
appContainer.classList.add('slide-out');
appContainer.classList.remove('slide-in');
} else {
appContainer.classList.remove('slide-out');
appContainer.classList.add('slide-in');
}
}
}
As explained in the answer, I really should not have been doing this. This DOM manipulation does NOT belong in the directive - nor anywhere else in AngularJS for that matter. So, I've removed that linking function from the directive and put the toggle function on a controller. In the controller method, I'm no longer manipulating the DOM. instead, I'm toggling a $scope variable that is used by ng-class to toggle the class applied to the main app container.
<article id="main-app" class="main-app-container" ng-class="{ 'menu-displayed': menuShown , 'menu-hidden': !menuShown }">
app.controller('MenuAndNavController', ['$scope', function($scope) {
$scope.menuShown = false;
$scope.toggleMenu = function() {
$scope.menuShown = !$scope.menuShown;
}
}]);
I've also changed the class used to create the slide-in, slide-out effect. The previous names ".slide-in" and ".slide-out" seemed to be class names that would apply to the menu section itself. In fact, they were applied to the main app container. it's the one doing the actual moving. I think this might have been confusing down the road to anyone using the template. They have been replaced with ".menu-displayed" and ".menu-hidden".
- Signup to find out when Kids In Touch launches