2016-09-14 23 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