How can I use ng-hide if $location.url == base (root) url?

All we need is an easy explanation of the problem, so here it is.

I’d like a ← Back to home link to appear below the nagivation on every page of my Angular app except the home page. So I’d like to conditionally add the link and hide it using ng-hide if the url is already on the home page (view) of the app.

I’ve tried using angular’s $location service with no success

<p ng-hide="location.hash == '#/'" class="container"><a href="#topics" rel="nofollow noreferrer noopener">&larr; Back to Home</a></p>

I’ve tried the following variations:

ng-hide="location.hash == '#/' " //console.log shows true
ng-hide="location.hash === '#/' " //console.log shows true
ng-hide="location.hash == '' "    //console.log shows false

I’m puzzled because if I log the value of location.hash == '#/' when on the home page i get true, so ng-hide should work.

Basically I’m trying the 3rd approach listed here:
How do I use angular ng-hide based on the page/route that I am currently on? But it’s not working. The other two approaches on that page seem overly complicated for what I’m trying to achieve.

What am I missing?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

First things first, when you use location.hash or location.url you are actually using the window.location javascript object, you should use the $location service provided by angular.
So in your controller I would create:

$scope.currentPath = $location.path();

And in your html:

<div ng-hide="currentPath === '/'"></div>

Tho I would be carefull about the “#/” and “/”, I only use the html5 mode so I’m not sure what the $location.path will return but you can easily check it with a console.log($location.path()) tho I think it will only return “/” because that’s the path for angular, it shouldn’t care about the #.

Method 2

Angular is looking for a $scope variable called location. If you want this to work you would have to do:

$scope.location = window.location

in your controller. But then you should really inject $location and set $scope.location = $location

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply