2016-09-14 77 views
2
绝对哈希

我试图让toState对象url$stateChangeStart事件的状态basic.taskstoState.url值不是嵌套状态

$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) { 
       ... 
        console.log(toState.name); // > basic.tasks 
        console.log(toState.url); // > /tasks 
       ... 
      } 

国家配置:

$stateProviderRef 
.state('basic',{ 
     url: '/b', 
     template: require('source/basic/templates/basic.html'), 
     controller: 'BasicController', 
     abstract: true 
     }) 
.state('basic.tasks', { 
     url: '/tasks', 
     template: require('source/basic/templates/tasks/tasks.html'), 
     controller: 'TasksController', 
     }) 

toState.url的值是/tasks而不是/b/tasks。有没有办法获得包括父状态在内的完整散列。

我尝试使用$window.location.hash,但它只给出fromState的完整散列路径,因为它在状态更改完成之前不会更新。

+0

您可以将引号添加到'BasicController'并重试吗?可能是第一个状态是由JS正确解释的 – Zakaria

+0

不好意思,这不是问题。我只是在这个问题中错过了控制器名称的引用。我会编辑它。 –

回答

1

有没有简单的方法来做到这一点,除非你只是将父状态添加到URL,但如果你正在寻找一种更动态的方式,那么这可能是一种选择。我不确定是否在你的url中有hashtag(通常它在那里,并且在这里我们使用它只是为了正则表达式去除hashtag - 但它在localhost中看起来像这样的http://localhost:8100/#/app),但如果你这样做,你可以尝试是这样的:

$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) { 
    var href = $state.href(toState.name); 
    var regexp = new RegExp('#','g'); 
    href = href.replace(regexp, ''); 
    console.log(href); 
}); 

如果你有你的网址一些状态参数可以用toParams将它们添加到绝对URL,因为参数没有被添加到与stateChangeStart此功能的URL。它将直接在stateChangeSuccess上运行。

编辑:

如Ganesh神Matkam在评论部分有说实际上是包括stateParams到URL一个简单的解决方案。就像这样简单:

$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) { 
    var href = $state.href(toState.name, toParams); 
    var regexp = new RegExp('#','g'); 
    href = href.replace(regexp, ''); 
    console.log(href); 
}); 
+0

哇,'$ state.href'是我的问题的解决方案。我搜索了'$ state.href'获取更多细节,并发现通过将params对象作为第二个参数传递给'$ state.href'函数也可以添加到url中:'var href = $ state.href( toState.name,toParams)'。所以请编辑您的答案,以便我接受它作为完美的解决方案。谢谢_thepio_。 –

+0

哦,对,我没有/没有太多的研究,但你的添加似乎完美。好的赶上!我编辑了我的答案,包括你的补充。 – thepio