Last active
December 27, 2015 04:09
-
-
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…
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
<!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> |
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
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