10

我希望← 返回主页链接出现在我的 Angular 应用程序的每个页面的导航下方,主页除外。所以我想有条件地添加链接并使用ng-hide如果 url 已经在应用程序的主页(视图)上隐藏它。

我尝试使用 Angular 的$location服务但没有成功

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

我尝试了以下变体:

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

我很困惑,因为如果我location.hash == '#/'在主页上记录我得到的时间值true,那么ng-hide应该可以工作。

基本上我正在尝试此处列出的第三种方法: 如何根据我当前所在的页面/路线使用角度 ng-hide?但它不起作用。对于我想要实现的目标,该页面上的其他两种方法似乎过于复杂。

我错过了什么?

4

2 回答 2

19

首先,当您使用 location.hash 或 location.url 时,您实际上是在使用 window.location javascript 对象,您应该使用 angular 提供的 $location 服务。所以在你的控制器中我会创建:

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

在你的 html 中:

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

虽然我会小心“#/”和“/”,但我只使用 html5 模式,所以我不确定 $location.path 会返回什么,但您可以使用 console.log($location .path()) 虽然我认为它只会返回“/”,因为那是 angular 的路径,它不应该关心#。

于 2014-07-24T21:01:04.333 回答
0

Angular 正在寻找一个$scope名为location. 如果你想让这个工作,你必须这样做:

$scope.location = window.location

在您的控制器中。但是你真的应该注入$location并设置$scope.location = $location

于 2014-07-24T20:58:35.530 回答