伙计我正在开发一个角度js应用程序,它使用ui-router
进行深层链接和路由。我想在每次访问/更改状态时在$rootScope
上设置变量。我可以通过监听$stateChangeSuccess
在后续的状态转换中实现这一点,但由于应用程序是深层链接的,因此我想在从地址栏直接命中状态时设置相同的变量。
当我从地址栏点击特定网址时,例如主页/摘要/更改,$stateChangeSuccess
不会触发,因此我无法设置值。
有关如何在$rootScope
上听取每次州访问的任何建议。
答案 0 :(得分:1)
您可以使用$locationChangeStart
和$route.current
的组合:
$rootScope.$on('$locationChangeStart', function (event, next, current) {
if(!$route.current) {
$rootScope.myVar = ...
}
});
答案 1 :(得分:0)
我为此找到了解决方法。第一次访问页面时我无法获得$stateChangeSuccess
因此在初始化时我明确调用了该函数。
示例代码
var handle = function(){
//do something ...
}
$scope.$on('$stateChangeSuccess', handle); // call handle on each state change
handle(); // will only be called on initialization
可能不是最干净的方式,但它有效
答案 2 :(得分:0)
与此同时,他们已经实施了$urlRouterProvider
,您可以在其中添加时间:
app.config(function($urlRouterProvider){
// when there is an empty route, redirect to /index
$urlRouterProvider.when('', '/index');
// You can also use regex for the match parameter
$urlRouterProvider.when(/aspx/i, '/index');
})
因此,如果您希望Home / Summary / Change匹配状态,您可以编写类似$urlRouterProvider.when('Home/Summary/Change','myhomestate')
的内容,然后$ stateChangeSuccess应该触发正确。
有关该提供商的更多详细信息,请查看https://github.com/angular-ui/ui-router/wiki/URL-Routing#urlrouterprovider