Episode 24 of 25

The Location Service

Learn how to use the $location service for URL manipulation and navigation.

The $location service lets you read and change the browser URL from within your AngularJS app.

Injecting $location

app.controller('NavCtrl', function($scope, $location) {
    $scope.currentPath = $location.path();
    $scope.currentUrl = $location.absUrl();
    $scope.searchParams = $location.search();
});

$location Methods

// Reading the URL
$location.path()       // Returns the current path, e.g. "/about"
$location.absUrl()     // Full URL: "http://example.com/#/about"
$location.url()        // Path + search + hash
$location.search()     // Query parameters as object
$location.hash()       // Hash fragment

// Changing the URL
$location.path('/contact');          // Navigate to /contact
$location.search({ page: 2 });      // Add query params
$location.hash('section1');          // Set hash

Practical Example — Navigation

app.controller('NavCtrl', function($scope, $location) {
    $scope.isActive = function(path) {
        return $location.path() === path;
    };

    $scope.goTo = function(path) {
        $location.path(path);
    };
});
<nav ng-controller="NavCtrl">
    <a href="#/" ng-class="{ active: isActive('/') }">Home</a>
    <a href="#/about" ng-class="{ active: isActive('/about') }">About</a>
    <button ng-click="goTo('/contact')">Contact Us</button>
</nav>

Listening for URL Changes

app.run(function($rootScope) {
    $rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
        console.log('Navigating from', oldUrl, 'to', newUrl);
    });

    $rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
        console.log('Route changed to:', current.$$route.originalPath);
    });
});