Skip to content

Instantly share code, notes, and snippets.

@smashercosmo
Last active December 27, 2015 04:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smashercosmo/7264729 to your computer and use it in GitHub Desktop.
Save smashercosmo/7264729 to your computer and use it in GitHub Desktop.
Quick implementation of angular's $route.reload() with ui-router. Ui-router has it's own $state.reload function, but it's behaviour differs from angular's. For example it can't reload a route (state) if it wasn't actually loaded. In this gist I use $locationChangeStart event to prevent route from being loaded, but then I reload it after 2 sec de…
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
<script src="http://angular-ui.github.io/ui-router/release/angular-ui-router.min.js"></script>
</head>
<body>
<div ui-view></div>
</body>
</html>
angular
.module('app', ['ui.router'])
.config(function($stateProvider){
$stateProvider.state('index', {
url: '/',
template: '<h1>{{ header }}</h1>',
controller: 'AppCtrl'
})
})
.controller('AppCtrl', function($scope){
$scope.header = "Hello, World!"
})
.run(function($timeout, $state, $location, $urlMatcherFactory){
$state.reload = function() {
var matchedState = null,
matchedStateParams = null;
angular.forEach($state.get(), function(state) {
var url = state.url ? $urlMatcherFactory.compile(state.url) : null,
params = url ? url.exec($location.path(), $location.search()) : null;
if (!matchedState && params) {
matchedState = state;
matchedStateParams = params;
}
});
$state.transitionTo(matchedState, matchedStateParams, { reload: true });
};
var condition = true;
$rootScope.$on('$locationChangeStart', function(event, next, prev) {
if(condition){
event.preventDefault();
$timeout(function(){
condition = false;
$state.reload();
}, 2000)
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment