Hide element outside the ng-view DOM based on route

徘徊边缘 提交于 2020-01-13 11:46:07

问题


Question:

How can I add a "Login" view/route to my angular app that hides an element that is outside the ng-view DOM?

Situation:

In my Angular page, I have a navigation tree view on the left and the main view in the center:

<div ng-app="myApp">
    <div class="col-sm-3" ng-controller="TreeController">
        <div treeviewdirective-here>
        </div>
    </div>
    <div class="col-sm-9 content" ng-view="">
    </div>
</div>

Each node in the treeview changes the location using something like window.location.hash = '#/' + routeForTheClickedItem;.

Using the standard routing, this works great, i.e. the tree is not reloaded each time, but only the main "window".

Problem:

I want to add a login functionality with a login view. For this view, the treeview should not be visible - only after the login. To achieve this with the normal routing, I know I could move the ng-view one level up, i.e. embed the treeview into each view - but this would result in the treeview being reloaded with every route change.

Is there an easy alternative that allows me to check what page is displayed in the ng-view? Or check some other variable set during the routing? Then I could use something like:

<div class="col-sm-3" ng-controller="TreeController" ng-show="IsUserLoggedIn">

回答1:


You could define a controller at the top div level.

Something like:

<div ng-app="myApp" ng-controller="MainController">

and in MainController inject a Session. Something like Session is enough to decide whether to show the tree.

Here's an example of MainController:

_app.controller('MainController', function ($scope, SessionService) {
    $scope.user = SessionService.getUser();
});

Here's an example of SessionService:

_app.factory('SessionService', function() {
    var user = null;
    return {
        getUser : function() {
            return user;
        },
        setUser : function(newUser) {
            user= newUser;
        }
    };
});

Of course, when you login you must set the user to the SessionService. Therefore, a SessionService has to be injected into your LoginController, too.

And finally, your html:

<div ng-app="myApp" ng-controller="MainController">
    <div class="col-sm-3" ng-controller="TreeController">
        <div ng-hide="user == null" treeviewdirective-here>
        </div>
    </div>
    <div class="col-sm-9 content" ng-view="">
    </div>
</div>



回答2:


You could listen for a routeChangeSuccess outside ng-view

$scope.$on('$routeChangeSuccess', function (event, currentRoute, previousRoute) {
//do something here
});

hope that helps, you can catch me on angularjs IRC - maurycyg



来源:https://stackoverflow.com/questions/22144227/hide-element-outside-the-ng-view-dom-based-on-route

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