Skip to content

Instantly share code, notes, and snippets.

@rwdcreative
Last active February 10, 2017 17:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwdcreative/da00e0fc23eef27d5d4ef4c3ce8ed39d to your computer and use it in GitHub Desktop.
Save rwdcreative/da00e0fc23eef27d5d4ef4c3ce8ed39d to your computer and use it in GitHub Desktop.
Simple UI-Router
// 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