How to hide templates with AngularJS ngView for unauthorized users?

后端 未结 2 1200
面向向阳花
面向向阳花 2021-02-04 11:06

I have a basic PHP app, where the user login is stored in the HTTP Session. The app has one main template, say index.html, that switch sub-view using ngView, like this



        
2条回答
  •  星月不相逢
    2021-02-04 11:09

    If you want to block them from going to that page create a service: http://docs.angularjs.org/guide/dev_guide.services.creating_services

    This service can be dependency injected by all your controllers that you registered with the routeParams.

    In the service you can would have a function that would check to see if the person is logged in or not and then re-route them (back to the login page perhaps?) using http://docs.angularjs.org/api/ng.$location#path. Call this function in each of the controllers like so:

    function myController(myServiceChecker){
        myServiceChecker.makeSureLoggedIn();
    }
    

    The makeSureLoggedIn function would check what current url they're at (using the $location.path) and if it's not one they're allowed to, redirect them back to a page that they are allowed to be.

    I'd be interested to know if there's a way to prevent the routeParams from even firing, but at least this will let you do what you want.

    Edit: Also see my answer here, you can prevent them from even going to the page:

    AngularJS - Detecting, stalling, and cancelling route changes

提交回复
热议问题