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

2

10

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">&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?

Bonded answered 24/7, 2014 at 20:33 Comment(1)
See this link for a similar question that was asked earlier: #24940820Beadroll
C
19

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 #.

Cuomo answered 24/7, 2014 at 21:1 Comment(4)
Ah, that's the step I was missing! I wasn't assigning $location.path() to anything in my controller. Thanks to you both!!Bonded
It just missing a double-quote here <div ng-hide="currentPath == '/'"></div> (but can't edit just for one character :( )Elfland
@Elfland Thanks for that, I just edited the answer and also added the "exactly equal" check.Cuomo
@Gino I guess that when your route changes you use a different controller, make sure all controllers have location in scope, or use a higher scope like rootScope.Cuomo
P
0

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

Procaine answered 24/7, 2014 at 20:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.