基于视图隐藏/显示元素

时间:2016-03-04 00:45:05

标签: javascript angularjs

我试图根据用户当前视图隐藏/显示div,但我遇到了一些问题。这是我的控制者:

angular.module('myApp')
  .controller('RouteCtrl', function ($scope, $location) {

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

});

在我的index.html中,我有这个:

<span ng-controller="RouteCtrl">
    <div ng-view=""></div>
    <div ng-include="'views/siderail.html'" ng-hide="currentPath === '/live'" ></div>
 </span>

在我的$routeProvider我有这个:

.when('/live', {
  templateUrl: 'views/live.html',
})

出于某种原因,这似乎不起作用。我希望在网站位于/ live路线时隐藏div,但它似乎没有做到这一点。如果我最初在加载时访问/ live,它将起作用,但一旦路由改变,它将不会重新显示div,反之亦然。几乎就像它检查一次,而不是像我想要的那样改变每一条路线。

2 个答案:

答案 0 :(得分:0)

在您的路线中包含控制器:

.when('/live', {
  controller: 'RouteCtrl',
  templateUrl: 'views/live.html',
})

答案 1 :(得分:0)

您需要注意位置更改,因为范围变量仅在加载控制器时定义一次。

将以下代码添加到控制器:

$scope.$on('$locationChangeSuccess', function() { 
     $scope.currentPath = $location.path();
});

这会在每次位置更改时更改范围变量。