onsa
12/17/2016 - 12:34 AM

Navigate between pages of an angular application (ngRoute).

Navigate between pages of an angular application (ngRoute).

//  set up event listener to keep track of which page we're on
$rootScope.$on('$locationChangeSuccess', function() {
    var pageName = $location.path().split('/', 2)[1];
    $rootScope.pageName = pageName;
});

//  manipulate url change
$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl, newState, oldState) {        //  oldState and newState are history state objects
    //  some condition
        {event.preventDefault();}         //  stops url change
});

//  somewhere else change the url
//  this will trigger the events above & will load the template / controller as specified in the route
$location.absUrl();                     //  gets full url
$location.url('/somePageName');         //  setter & getter
$location.path('/somePageName');        //  setter & getter - same as url but without parameters
$location.search('key', 'value');       //  setter: sets ?key = value in url ; getter: returns {key: 'value'}

//  next location change will replace last history record instead of creating a new one
//  handy for changing url without creating new history record
$location.replace();