-1

In my angular application I have a menu with a set of links, I have put the links in an angular directive and I want to use the current location to decide if a link is active and then add a css class to it.

What I have done so far is this: (stripped to the relevant stuff)

angular.module(‘myNavigation’).directive(‘navItem’, ['$location', function($location) {

    console.log($location.absUrl());
    console.log($location.path());

    return {
        restrict: ‘EA’,
        scope: true,
        link: function (scope) {
            isCurrentLink = angular.equals(scope.item.href,$location.absUrl());
        },
        template: ‘<a ng-href=”{{item.href}}” ng-class=”{active:isCurrentLink}”>{{item.name}}</a>”
}
}]);

This works fine, but only if I put complete urls in the data for my navigation including domainname etc. But the url’s in the navigation data received by my directive do not contain domain name / protocol etc.

Then first console.log gives me the full URL but the second returns an empty string. For some reason I cannot acces $location.path() in my directive. What am i doing wrong?

By the way i do have a path, my application is not on the default page in the root folder.

UPDATE

I just discovered that $location.path() returns the part of the url after the hash(#), I was expecting it to return the part of the url without protocol, servername and serverport.

So when i go to https://stackoverflow.com/posts/25894149/, I'd want to have posts/25894149/.

Can i use $location to achieve this?

Community
  • 1
  • 1
Michiel
  • 4,160
  • 3
  • 30
  • 42

1 Answers1

1

I found out that $location cannot give this information.

When you include $window instead, you can ask for $window.location.pathname which gave me exactly what I needed.

for example when you url is: url: http://stackoverflow.com/questions/25894149/#something

$window.location.pathname wil return /questions/25894149/

Michiel
  • 4,160
  • 3
  • 30
  • 42