![](/img/trans.png)
[英]Retaining/passing parameters across deep states with angular and ui-router
[英]angular ui-router passing values to states from html
我有2條需要參數的路線。 一個是另一個的父項:
/a/:a_value/b/:b_value
文檔說“導航到帶有參數的狀態”。 做:
ui-sref='stateName({param: value, param: value})'
但是當我嘗試這樣做時不起作用:
//in controller: $scope.aValue = 1; $scope.bValue = 2; //in router config: .state("a", { url: "/a/:a_value" }) .state("ab", { url: "/b/:b_value" });
this works correctly: <a ng-href="/a/{{aValue}}/b/{{bValue}}">the angular way</a> it outputs: <a href="/a/1/b/2">the angular way</a> this doesn't work correctly: <a ui-sref="ab({a_value: a_value, b_value: bValue })">the ui-router way?</a> it outputs: <a href="/a/b/">the ui-router way?</a>
假設其他所有內容在我的應用程序中均正常運行,那不行嗎?
您第三次嘗試幾乎是對的。 下面的代碼行應該已經起作用。 (假設其余所有都是正確的)
<li><a href ui-sref="a.b({a_value: 1, b_value: 2})">b</a></li>
ui-router文檔確實警告用戶有關常見的陷阱 。 我不確定您是否考慮到了這一點,但它絕對適用於此給定的用例。
重要的$ stateParams陷阱
在狀態控制器中,$ stateParams對象將僅包含在該狀態下注冊的參數。 因此,您不會看到在其他州(包括祖先)注冊的參數。
$stateProvider.state('contacts.detail', {
url: '/contacts/:contactId',
controller: function($stateParams){
$stateParams.contactId //*** Exists! ***//
}
}).state('contacts.detail.subitem', {
url: '/item/:itemId',
controller: function($stateParams){
$stateParams.contactId //*** Watch Out! DOESN'T EXIST!! ***//
$stateParams.itemId //*** Exists! ***//
}
})
但是,您仍然可以將具有多個屬性的對象傳遞給您的狀態,只要它包含匹配的參數即可。 我算出了您發布到正在工作的插件中的代碼。
$stateProvider.state("a", {
url: "/a/:a_value",
templateUrl: 'a.html',
controller: 'AController as a'
});
$stateProvider.state("a.b", {
url: "/b/:b_value",
templateUrl: 'b.html',
controller: 'BController as b'
});
使用以下導航:
<body>
<nav>
<ul>
<li><a href ui-sref="a({a_value: 3})">a</a></li>
<li><a href ui-sref="a.b({a_value: 1, b_value: 2})">b</a></li>
</ul>
</nav>
<div ui-view></div>
</body>
您可以根據需要使用范圍參數替換a_value和b_value的值。 由於b是a的子元素,因此它將在其父模板中搜索嵌套的ui-view,因此請確保提供一個。
<h1>{{a.hello}}</h1>
{{a.$stateParams}}
<ui-view></ui-view>
您可以在plunker上找到完整的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.