Is it possible to get the current $location in a directive in Angular JS?

thought injecting service into directive it still gets undefined into link function, for that you need to use

location.hash = "#/path_name";

in link function it will work


In the declaration of the directive, inject the location service.

app.directive('myDirective', ['$location', function($location) {

 return {
  link: function(scope, elem, attrs) {
   // path() and url() can be used as getters or setters
   console.log($location.url());
   console.log($location.path());
  }
 };
}]);

If you are attempting to get the current location, use location.path() or, alternatively, use the $route service.

Information on both:

  1. $route Docs
  2. $location Docs