问题描述
有一个工作的傻瓜。
它来自类似的问题:AngularJS ui-router-两个相同的路由组
如果我确实正确理解了您的目标,这将是调整后的状态定义 (我只是跳过了$ 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 : {}
成为: 。另一个是控制器定义(rt vs
type)。而且,我们从内置的功能做利润templateProvider
和$templateRequest
(类似于此:
角ui.router重载父templateProvider)
在这里检查动作
EXTEND,包括$http部分(扩展的plunker)
让我们调整(出于更矮小的目的)服务器部分以将此信息返回为 :
{
"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
})
}
]
}
})
解决方法
可通过API访问的服务器数据库中的示例实例:
{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调用到服务器的数据段创建动态状态。
我写了一个 假想的代码。 但是我没有办法实现
// 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
}
}
})