Skip to content

Instantly share code, notes, and snippets.

@ifraixedes
Last active August 29, 2015 14:06
Show Gist options
  • Save ifraixedes/f03e2ea7066a2a289925 to your computer and use it in GitHub Desktop.
Save ifraixedes/f03e2ea7066a2a289925 to your computer and use it in GitHub Desktop.
Executing Angular App from non-root URL, doing all the operations and loading the required route (external social networks login is one of the use cases)
angular.module('simplified', ['ng-route'])
.config([
'$routeProvider',
function ($router) {
$router.when('/', {
templateUrl: '/views/main.html',
controller: 'MainCtrl'
});
}
])
.run([
'$location',
'routeTracker',
function ($location, routeTracker) {
// Check if SPA has been requested from a diffent
// main URL
if ($location.path() !== '/') {
// Track the current URL to redirect to it
// after the application state restore (MaintCtrl)
routeTracker.track($location.url());
// Change the URL to execute (MainCtrl)
// Because it is changed here, previous
// URL never has been executed, `run`
// execute before to execute the controller
// associated with the route
$location.url('/');
}
}
]);
angular.module('simplified')
.controller('MainCtrl', [
'$location',
'routeTracker',
// The other services which are required
// to inject to use in the controller
function ($location, routeTracker /*the rest of services*/) {
// Make all the operations that you require,
// e.g. load data from local store, make request to the server
// to pull last status, etc.
// If tracker has a tracked route
if (routeTracker.isRouteTracked()) {
// Get the route and load the tracked local route
$location.url(routeTracker.pop());
}
}
]);
// Very simple service
anguar.module('simplified')
.factory('routeTracker', function () {
var trackedUrl = null;
return {
isRouteTracked: function () {
return (trackedUrl === null) ? false : true;
},
track: function (url) {
trackedUrl = url;
},
pop: function () {
var url = trackedUrl;
trackedUrl = null;
return url;
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment