Last active
March 21, 2017 02:22
-
-
Save martianyi/41131c3fb467843fba6e to your computer and use it in GitHub Desktop.
angularjs service to update settings when route change
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
var routeData = angular.module('RouteData', []); | |
routeData.provider('RouteData', function () { | |
var settings = {}; | |
var hookToRootScope = false; | |
this.applyConfig = function (newSettings) { | |
settings = newSettings; | |
}; | |
this.hookToRootScope = function (enableRootScopeHook) { | |
hookToRootScope = enableRootScopeHook; | |
}; | |
function RouteData() { | |
this.set = function (index, value) { | |
settings[index] = value; | |
}; | |
this.get = function (index) { | |
if (settings.hasOwnProperty(index)) { | |
return settings[index]; | |
} else { | |
console.log('RouteData: Attempt to access a propery that has not been set'); | |
} | |
}; | |
this.isHookedToRootSope = function () { | |
return hookToRootScope; | |
}; | |
} | |
this.$get = function () { | |
return new RouteData(); | |
}; | |
}); | |
routeData.run(['$location', '$rootScope', 'RouteData', function ($location, $rootScope, RouteData) { | |
if (RouteData.isHookedToRootSope()) { | |
$rootScope.RouteData = RouteData; | |
} | |
$rootScope.$on('$routeChangeStart', function (event, current, previous) { | |
var route = current.$$route; | |
if (typeof(route) !== 'undefined' && typeof(route['RouteData']) !== 'undefined') { | |
var data = route['RouteData']; | |
for (var index in data) | |
RouteData.set(index, data[index]); | |
} | |
}); | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment