UNPKG

angular-state-router

Version:

An AngularJS state-based router designed for flexibility and ease of use.

77 lines (59 loc) 1.45 kB
'use strict'; var UrlDictionary = require('../utils/url-dictionary'); module.exports = ['$state', '$location', '$rootScope', function($state, $location, $rootScope) { var _url = $location.url(); // Instance var _self = {}; /** * Update URL based on state */ var _update = function() { var current = $state.current(); if(current && current.url) { var path; path = current.url; // Add parameters or use default parameters var params = current.params || {}; var query = {}; for(var name in params) { var re = new RegExp(':'+name, 'g'); if(path.match(re)) { path = path.replace(re, params[name]); } else { query[name] = params[name]; } } $location.path(path); $location.search(query); _url = $location.url(); } }; /** * Update url based on state */ _self.update = function() { _update(); }; /** * Detect URL change and dispatch state change */ _self.location = function() { var lastUrl = _url; var nextUrl = $location.url(); if(nextUrl !== lastUrl) { _url = nextUrl; $state.$location(_url); $rootScope.$broadcast('$locationStateUpdate'); } }; /** * Register middleware layer */ _self.$ready = function() { $state.$use(function(request, next) { _update(); next(); }); }; return _self; }];