how to bind the relevant value in case of current status in ui-router?

感情迁移 提交于 2019-12-04 16:42:52

You can solve your problem in a very cleaner way. Let's start with a global controller example GlobalCtrl which is added to the body or html tag like ng-controller="GlobalCtrl.

Doing this will enable us to keep the scope of this GlobalCtrl throughout your single page Angular app (as you are using ui-router) and we can avoid the usage of $rootScope (actually mimicking the usage of $rootScope).

Now, inside your GlobalCtrl define something like this:

// Using an object to avoid the scope inheritance problem of Angular
// https://github.com/angular/angular.js/wiki/Understanding-Scopes
$scope.globalData = {};

// Will be called everytime before you start navigating to any state
$scope.$on('$stateChangeStart', function(event, toState, toParams) {
    $scope.globalData.requireLogin = false;
    var statesToLoginCheck = ['403', 'foo', 'bar']; // and other states on which you want to check if user is logged in or not

    // If the current state on which we are navingating is allowed to check for login
    if (statesToLoginCheck.indexOf(toState.name) > -1) {
        if (Auth.isAuthenticated()) {
            $scope.globalData.requireLogin = true;
            $state.go('admin-panel.default.home');
        } else {
            $scope.globalData.requireLogin = false;
            $state.go('admin-panel.public.home');
        }

        event.preventDefault();
        return;
    }
});

Now, since $scope of GlobalCtrl is in body or html then every state or directive will inherit the scope of this GlobalCtrl and then you simply have to check in your any controller of variable $scope.globalData.requireLogin.

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