AngularJS: 访问 $routeProvider 中的作用域变量
AngularJS: accessing scope variables in $routeProvider
我在 JSP 页面上有一个 angular 应用程序,该应用程序具有:
ng-init="role='<%=String.valueOf(session.getAttribute("role"))%>'"
所以当 JSP 从会话中拉取角色属性时,正文标签将如下所示:
<body ng-app="appName" ng-init="role='roleName'">
我想访问 $routeProvider
中的这个 role
变量。
我尝试通过将 $scope
传递给 app.config
函数来这样做:
app.config(['$routeProvider', '$scope',
function ($routeProvider, $scope) {
$routeProvider
.when('somePath' {
...
})
.when('someOtherPath' {
...
})
.otherwise({
redirectTo: $scope.role == 'goodRole' ? 'somePath' : 'someOtherPath'
});
}]);
但是,您似乎无法通过这种方式传入 $scope
。
有没有办法以这种方式访问作用域变量,或者有其他方法可以做到这一点?
不,这不可能像您尝试的那样,因为 configuration phase(创建和配置服务)发生在 之前 运行 阶段(控制器 运行,呈现的指令,链接的范围)。
在您的情况下,您可能希望创建全局变量并从配置块访问它。在这种情况下,您实际上没有太多选择。
另请查看 this answer 我提供的关于将全局变量配置注入 Angular 应用程序的类似主题。
不,这不可能。你如何将它设置为 data-role
属性并从 document.body.dataset.role
:
获取它?
data-role="<%=String.valueOf(session.getAttribute("role"))%>"
我在 JSP 页面上有一个 angular 应用程序,该应用程序具有:
ng-init="role='<%=String.valueOf(session.getAttribute("role"))%>'"
所以当 JSP 从会话中拉取角色属性时,正文标签将如下所示:
<body ng-app="appName" ng-init="role='roleName'">
我想访问 $routeProvider
中的这个 role
变量。
我尝试通过将 $scope
传递给 app.config
函数来这样做:
app.config(['$routeProvider', '$scope',
function ($routeProvider, $scope) {
$routeProvider
.when('somePath' {
...
})
.when('someOtherPath' {
...
})
.otherwise({
redirectTo: $scope.role == 'goodRole' ? 'somePath' : 'someOtherPath'
});
}]);
但是,您似乎无法通过这种方式传入 $scope
。
有没有办法以这种方式访问作用域变量,或者有其他方法可以做到这一点?
不,这不可能像您尝试的那样,因为 configuration phase(创建和配置服务)发生在 之前 运行 阶段(控制器 运行,呈现的指令,链接的范围)。
在您的情况下,您可能希望创建全局变量并从配置块访问它。在这种情况下,您实际上没有太多选择。
另请查看 this answer 我提供的关于将全局变量配置注入 Angular 应用程序的类似主题。
不,这不可能。你如何将它设置为 data-role
属性并从 document.body.dataset.role
:
data-role="<%=String.valueOf(session.getAttribute("role"))%>"