AngularJS: accessing scope variables in $routeProvider

試著忘記壹切 提交于 2019-12-11 02:49:13

问题


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?


回答1:


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"))%>"




回答2:


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.



来源:https://stackoverflow.com/questions/29630268/angularjs-accessing-scope-variables-in-routeprovider

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