Last active
February 10, 2017 17:17
-
-
Save rwdcreative/da00e0fc23eef27d5d4ef4c3ce8ed39d to your computer and use it in GitHub Desktop.
Simple UI-Router
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Default Path | |
var defaultPath = 'home' | |
// Set Default State | |
history.pushState(null, null, '#/' + defaultPath); | |
// Custom UI Routing | |
function uiRouter(){ | |
// Create URL Path Array | |
if(window.location.hash) { | |
var str = window.location.hash; | |
var n = str.indexOf('/'); | |
var result = str.substring(n + 1); | |
var pathArray = result.split( '/' ); | |
route(pathArray); | |
} else { | |
// go to default page | |
history.pushState(null, null, '#/' + defaultPath); | |
} | |
//Routing Functions | |
function route(pathArray){ | |
switch (pathArray[0]) { | |
case "home": | |
console.log("on home page!"); | |
break; | |
case "about": | |
console.log("on about page!"); | |
break; | |
default: | |
history.pushState(null, null, '#/' + defaultPath); | |
} | |
} | |
} | |
window.onpopstate = function (event) { | |
if (event.state) { | |
// history changed because of pushState/replaceState | |
uiRouter(); | |
} else { | |
// history changed because of a page load | |
uiRouter(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment