The $location
service in AngularJS is responsible for parsing the URL from the browser address bar and making it available to your application. In order to use regular URL path and search segments, you need to set html5Mode
to true with $locationProvider
.
By default, $locationProvider
uses hashbangs. If you don't enable html5Mode
, attempting to fetch the URL path will result in an empty string.
Once you have set up html5mode
, you can leverage the $location
service to retrieve the URL path and create custom rules for processing it.
For instance, if your full URL looks like:
http://example.com/person/show/321
In your main.js
file, you could have:
angular.module("MyAPP",[],function($locationProvider){
$locationProvider.html5Mode(true);
});
function MainController($location){
var pId = $location.path().split("/")[3]||"Unknown"; //path will be /person/show/321/, and array looks like: ["","person","show","321",""]
console.log(pId);
}
And in your index.html
file:
<!DOCTYPE html>
<html lang="en" ng-app="MyAPP">
<head>
<meta charset="utf-8">
<title>Angular test</title>
</head>
<body ng-controller="MainController">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
I hope this information proves useful to you.