2014-11-01 117 views
0

div元素,我有以下结构:AngularJs隐藏特定路径/控制器

<html> 
<head> 
     // additional info here 
</head> 

<body data-ng-app="myApp" data-ng-controller="contentController"> 
     <div id="container"> 

      <div id="id1"> 
       //content here 
      </div> 

      <div id="id2"> 
       //content here 
      </div> 

      <div id="id3"> 
       //content here 
      </div> 

      <div id="page-content"> 
       <div data-ng-view=""> 
        //here will be loaded the other views 
        //Example: /profile, /login, /register, etc etc) 
       </div> 
      </div> 

     </div> 
</body> 
</html> 

我需要的是隐藏divs: id1, id2, id3当用户导航到像/登录或注册的特定页面。对于所有其他页面,divs: id1, id2, id3应该是可见的。

当用户导航到/login时,divs: id1, id2, id3内容与登录表单一起显示,因此我必须以某种方式隐藏它。

divs: id1, id2, id3对于除/login,/register/forgot之外的所有页面都是常见的。

回答

1

您可以使用从$ rootScope播出的$locationChangeSuccess事件来检查当前使用$route服务的路线。这种方法的优点是,仍然可以检测到通过使用地址栏的导航。

DEMO

JAVASCRIPT

.controller('contentController', function($scope, $rootScope, $route) { 

    var paths = ['/login', '/register', '/forgot']; 

    $rootScope.$on('$locationChangeSuccess', function() { 

     var $$route = $route.current.$$route; 
     $scope.contentVisibility = $$route && paths.indexOf($$route.originalPath) < 0; 

    }); 

    }); 

HTML

<body data-ng-app="myApp" data-ng-controller="contentController"> 
    <div id="container"> 
     <div id="id1" ng-show="contentVisibility"> 
       //content here 
      </div> 
     <div id="id2" ng-show="contentVisibility"> 
       //content here 
      </div> 
     <div id="id3" ng-show="contentVisibility"> 
       //content here 
     </div> 
     <div id="page-content"> 
     <div data-ng-view=""> 
      //here will be loaded the other views 
      //Example: /profile, /login, /register, etc etc) 
     </div> 
     </div> 

     <!-- list of routes bound within the anchor tags --> 
     <a ng-repeat="path in [ 
      '/login', '/register', '/forgot', 
      '/other-route-1', '/other-route-2', '/other-route-3']" 
      ng-href="#{{path}}">{{path}}<br></a> 

    </div> 
    </body> 
0

您应该使用data-ng-hide隐藏您的内容。但是,您必须在特定控制器的开始处设置变量以隐藏内容,而在其他控制器中,您应该将其设置为false以显示内容。

在特定控制器的开头:

var $scope.contentHide = true; 

在其他控制器的开头:

var $scope.contentHide = false; 

<div id="id1" data-ng-hide="contentHide"> 
       //content here 
</div> 

<div id="id2" data-ng-hide="contentHide"> 
       //content here 
</div> 

<div id="id3" data-ng-hide="contentHide"> 
       //content here 
</div> 
+0

因此,这意味着我不需要验证或至少护理的url位置或做一个检查什么是当前的网址,如:$ scope.contentHide = $ location.path()==='/ login''对不对? – 2014-11-01 05:50:40

+0

不,你不需要这个 – 2014-11-01 05:52:50

+0

还有一个问题,关于控制器,你可以在上面的html中看到,当我进入/登录登录视图时,将加载到'data-ng-view'内,控制器用于/ login在登录视图中声明。该属性是否适用于div'data-ng-view'上面的元素? – 2014-11-01 05:54:29