Last active
August 24, 2017 21:54
-
-
Save joaoneto/1c290257eda61732145fa13d363f019f to your computer and use it in GitHub Desktop.
This file contains 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
(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