The $location
service in AngularJS is used to manipulate the browser’s URL without reloading the page. It provides methods to read and modify different parts of the URL, such as the path, search parameters, and hash fragments.
1. Why Use $location
?
✔ Update URL Without Reloading – Change the browser URL dynamically.
✔ Read URL Parameters – Extract query parameters from the URL.
✔ Improve Navigation – Redirect users programmatically.
✔ Manage Hash-Based Routing – Useful for single-page applications (SPA).
2. Basic Usage of $location
Before using $location
, make sure the ngRoute
module is included in your AngularJS app.
var app = angular.module("myApp", ["ngRoute"]);
app.controller("MainController", ["$scope", "$location", function($scope, $location) {
$scope.currentPath = $location.path(); // Get the current URL path
}]);
How It Works:
$location.path()
retrieves the current URL path.- If the URL is
http://example.com/#/dashboard
,$scope.currentPath
will be"/dashboard"
.
3. Modifying the URL
You can change the URL dynamically using $location.path()
.
Example: Redirecting to Another Page
$scope.goToProfile = function() {
$location.path("/profile"); // Updates the URL to "/profile"
};
How It Works:
- Calling
$scope.goToProfile()
changes the browser URL without reloading. - The app will navigate to
/profile
based on the$routeProvider
configuration.
4. Working with Query Parameters ($location.search()
)
Query parameters allow passing extra data in the URL (?key=value
).
Setting Query Parameters
$location.search("user", "Narendra");
$location.search("role", "admin");
Updates the URL to:http://example.com/#/dashboard?user=Narendra&role=admin
Getting Query Parameters
Retrieve query parameters using $location.search()
:
var user = $location.search().user;
var role = $location.search().role;
console.log(user, role); // Output: Narendra admin
Removing Query Parameters
To remove a specific query parameter, pass null
:
$location.search("role", null);
Updates the URL to:http://example.com/#/dashboard?user=Narendra
5. Managing Hash Values ($location.hash()
)
A hash (#
) in the URL represents an anchor to a specific section.
Setting a Hash Value
$location.hash("section2");
Updates the URL to:http://example.com/#/dashboard#section2
Retrieving the Hash Value
var currentHash = $location.hash();
console.log(currentHash); // Output: section2
6. Listening to URL Changes ($watch
)
You can detect when the URL changes using $watch
.
$scope.$watch(function() {
return $location.path();
}, function(newPath) {
console.log("URL changed to:", newPath);
});
How It Works:
- Whenever the URL path changes, the function logs the new path.
7. Preventing Reload on URL Change
By default, $location.path()
changes the URL without reloading. However, if you want to force a reload:
javascriptCopyEdit$location.path("/dashboard").replace();
The .replace()
method updates the URL without adding an entry in the browser history.
8. Example: Full Implementation
HTML (index.html
)
<div ng-app="myApp" ng-controller="MainController">
<p>Current Path: {{ currentPath }}</p>
<button ng-click="goToProfile()">Go to Profile</button>
<button ng-click="addQueryParam()">Add Query Parameter</button>
</div>
JavaScript (app.js
)
var app = angular.module("myApp", ["ngRoute"]);
app.controller("MainController", ["$scope", "$location", function($scope, $location) {
$scope.currentPath = $location.path();
$scope.goToProfile = function() {
$location.path("/profile");
};
$scope.addQueryParam = function() {
$location.search("user", "Narendra");
};
$scope.$watch(function() {
return $location.path();
}, function(newPath) {
console.log("URL changed to:", newPath);
});
}]);
9. Summary
Feature | Method | Example |
---|---|---|
Get Current Path | $location.path() | $location.path(); |
Change URL Path | $location.path(newPath) | $location.path("/dashboard"); |
Add Query Parameters | $location.search(key, value) | $location.search("user", "Narendra"); |
Get Query Parameters | $location.search().key | $location.search().user; |
Remove Query Parameter | $location.search(key, null) | $location.search("role", null); |
Set Hash Value | $location.hash(value) | $location.hash("section2"); |
Get Hash Value | $location.hash() | $location.hash(); |
Prevent Reload | $location.replace() | $location.path("/dashboard").replace(); |