Skip to content

Instantly share code, notes, and snippets.

@joaoneto

joaoneto/dynamicStates.js

Last active Aug 24, 2017
Embed
What would you like to do?
(function() {
'use strict';
var dynamicStates = function ($stateProvider, $urlRouterProvider) {
var addRoute = function (name, definition) {
$stateProvider.state(name, definition);
};
$urlRouterProvider.deferIntercept();
var addRoutes = function (dynamicRoutesConfig) {
for (var routeName in dynamicRoutesConfig) {
addRoute(routeName, dynamicRoutesConfig[routeName]);
}
};
this.addRoute = addRoute;
this.addRoutes = addRoutes;
this.$get = ['$q', '$http', '$urlRouter', '$rootScope', function dynamicRoutesFactory($q, $http, $urlRouter, $rootScope) {
var defered = $q.defer();
var fetchRoutes = function (url) {
$rootScope.$on('$locationChangeSuccess', function (e) {
e.preventDefault();
defered.promise.then(function () {
$rootScope.$evalAsync(function () {
$urlRouter.sync();
});
});
});
$urlRouter.listen();
return $http.get(url, { cache: true })
.then(function (response) {
addRoutes(response.data);
defered.resolve();
return response.data;
}).catch(defered.reject);
};
return {
fetchRoutes: fetchRoutes
};
}];
};
angular.module('dynamic-states', ['ui.router'])
.provider('dynamicStates', ['$stateProvider', '$urlRouterProvider', dynamicStates]);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.