This article describes how to use AngularJS to implement scalable page switching. AngularJS is a popular JavaScript library, for more information, see AngularJS 1.2. By introducing pure CSS class-based switches and animations, it is easier to create page-to-page switches in a single page application. You only need to use one ng-view. Let's take a look at a number of scalable methods that introduce different switches and how to cut in and out each specified page.
Demo: http://embed.plnkr.co/PqhvmW/preview
First, mark:
Since ng-view uses the entry/exit animation, two ng-view elements can be used in the DOM to cut the New view and the old view. Therefore, in the relative positioning page-container element, ng-view is created using absolute positioning to support any location switching.
'Go' Method
In a single page application, we still want to enable URL navigation and ensure that the browser's back-up and next buttons are as expected. So once we set our routes, templates, and controllers in $ routeProvider (optional resolution), we can use a relative path in a ng-click to directly switch the page:
Go to page 2
This can also work, but we need to specify to switch a class in ng-view hard encoding. Instead, let's create a 'Go' Method on $ rootScope, so that we can specify a path and a switch like this:
Go to page 2
Here is the $ rootScope 'Go' method:
$rootScope.go = function (path, pageAnimationClass) { if (typeof(pageAnimationClass) === 'undefined') { // Use a default, your choice $rootScope.pageAnimationClass = 'crossFade'; } else { // Use the specified animation $rootScope.pageAnimationClass = pageAnimationClass; } if (path === 'back') { // Allow a 'back' keyword to go to previous page $window.history.back(); } else { // Go to the specified path $location.path(path); }};
Now, any switch class specified by your second parameter will be added to ng-view, and the go method will change the page path with the specified first parameter.
Switch class
The next step is to create an arbitrary number of switching classes and use the hooks provided by the ngAnimate module. For example:
/* slideLeft */.slideLeft { transition-timing-function: ease; transition-duration: 250ms;} .slideLeft.ng-enter { transition-property: none; transform: translate3d(100%,0,0);} .slideLeft.ng-enter.ng-enter-active { transition-property: all; transform: translate3d(0,0,0);} .slideLeft.ng-leave { transition-property: all; transform: translate3d(0,0,0);} .slideLeft.ng-leave.ng-leave-active { transition-property: all; transform: translate3d(-100%,0,0);}