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

余生颓废 提交于 2019-12-20 22:56:13

问题


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?


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




回答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



来源:https://stackoverflow.com/questions/24943453/how-can-i-use-ng-hide-if-location-url-base-root-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!