AngularJS: accessing scope variables in $routeProv

2019-07-21 06:29发布

I have an angular app on a JSP page that has:

ng-init="role='<%=String.valueOf(session.getAttribute("role"))%>'"

So the body tag will look like this when the JSP pulls the role attribute from the session:

<body ng-app="appName" ng-init="role='roleName'">

I want to access this role variable in the $routeProvider.

I tried doing so by passing $scope to the app.config function as such:

app.config(['$routeProvider', '$scope',
    function ($routeProvider, $scope) {
        $routeProvider
        .when('somePath' {
            ...
        })
        .when('someOtherPath' {
            ...
        })
        .otherwise({
            redirectTo: $scope.role == 'goodRole' ? 'somePath' : 'someOtherPath'
        });
}]);

However, it appears that you cannot pass in the $scope that way.

Is there a way to access a scope variable in this fashion, or is there another way to accomplish this?

2条回答
▲ chillily
2楼-- · 2019-07-21 06:55

No, it's not possible like you are trying, because configuration phase (services are created and configured) takes place before run phase (controllers run, directives rendered, scopes linked).

in your case you will probably want to create global variable and access it from config block. In this case you don't have many options really.

Also check this answer I provided on the somewhat similar topic about injecting global variable configuration into Angular app.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-21 06:59

Nope, it is not possible. How about you set it to a data-role attribute and get it from document.body.dataset.role:

data-role="<%=String.valueOf(session.getAttribute("role"))%>"

查看更多
登录 后发表回答