可通过API访问的服务器数据库中的slu ::
{slug: "john-smith",type: "user"}
{slug: "microsoft-technologies",type: "company"}
方案1:用户视图&控制器:http://localhost/john-smith
.state('user', {
url: '/:user',
templateUrl: 'partial-user.html',
controller: 'userCtrl'
})
方案2:公司视图&控制器:http://localhost/microsoft-technologies
.state('company', {
url: '/:company',
templateUrl: 'partial-company.html',
controller: 'companyCtrl'
})
现在我想根据从API调用到服务器的slug来制作一个动态状态。
我写了一个虚构代码。但是我没有办法实现
// Example URL http://localhost/john-smith
.state('hybrid', {
// /john-smith
url: '/:slug',
templateUrl: function () {
return "partial-"+type+".html"
},
controllerProvider: function (rt) {
return type+'Controller'
},
resolove: {
type: function ($http, $stateParams) {
$http.get({
method: "GET",
url: "http://localhost/api/" + $stateParams.slug
}).success(function(response, status, headers, config){
//response = {slug: "john-smith",type: "user"}
return response.type
})
return
}
}
})
答案 0 :(得分:10)
它来自类似的问题:AngularJS ui-router - two identical route groups
如果我确实理解你的目标,这将是调整后的状态定义(我刚刚跳过$ http和服务器响应部分,只是使用传递的参数):
.state('hybrid', {
// /john-smith
url: '/{slug:(?:john|user|company)}',
templateProvider: ['type', '$templateRequest',
function(type, templateRequest)
{
var tplName = "tpl.partial-" + type + ".html";
return templateRequest(tplName);
}
],
controllerProvider: ['type',
function(type)
{
return type + 'Controller';
}
],
resolve: {
type: ['$http', '$stateParams',
function($http, $stateParams) {
/*$http.get({
method: "GET",
url: "http://localhost/api/" + $stateParams.slug
}).success(function(response, status, headers, config){
//response = {slug: "john-smith",type: "user"}
return response.type
})*/
return $stateParams.slug
}
]
}
})
resolove : {}
变为: resolve : {}
。另一个是控制器def的固定(rt vs type)。此外,我们从内置功能templateProvider
和$templateRequest
(类似于此处:Angular ui.router reload parent templateProvider)
检查行动here
EXTEND,包括$ http部分(extended plunker)
让我们调整(用于吸引人)服务器部件,将此信息作为 data.json
返回:
{
"john-smith": {"type": "user"},
"lady-ann": {"type": "user"},
"microsoft-technologies" : {"type": "company" },
"big-company" : {"type": "company" },
"default": {"type" : "other" }
}
这些链接:
<a href="#/john-smith">
<a href="#/lady-ann">
<a href="#/microsoft-technologies">
<a href="#/big-company">
<a href="#/other-unknown">
将通过此调整状态def轻松管理:
.state('hybrid', {
// /john-smith
url: '/:slug',
templateProvider: ['type', '$templateRequest',
function(type, templateRequest)
{
var tplName = "tpl.partial-" + type + ".html";
return templateRequest(tplName);
}
],
controllerProvider: ['type',
function(type)
{
return type + 'Controller';
}
],
resolve: {
type: ['$http', '$stateParams',
function($http, $stateParams) {
return $http.get("data.json")
.then(function(response){
var theType = response.data[$stateParams.slug]
||response.data["default"]
return theType.type
})
}
]
}
})