简体   繁体   中英

Use directive as value for ng-if?

In my application, I need to be able to easily determine whether a user is authenticated within my HTML and in all templates.

My first thought on how to do this was to create a "global" controller and apply it to which simply set $scope.isAuthenticated = $auth.isAuthenticated.

However, after doing some reading, I discovered that this wasn't considered good practice. Instead, I created a directive, which would just return $auth.isAuthenticated().

angular.module('HordeWebClient')
  .directive('isAuthenticated', function($auth) {
    return $auth.isAuthenticated();
  });

And then in my templates, I figured I could just use .... This doesn't work, the element isn't rendered regardless of the state of $auth.isAuthenticated.

The Safari error console doesn't show any problems, so I'm stuck on where to start in fixing this. Any pointers would be greatly appreciated.

In my opinion you should use .run on your main module.

angular.module('app').run(function(){
    if(!isAuthenticated){
        redirectToLoginView();
    }
});

More: https://docs.angularjs.org/guide/module

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM