问题描述
我试图加载基于一个stateparam控制器,使其可重复使用
I am trying to load a controller based on a stateparam to make it reusable
.state("dashboard.item.detail", {
url: "/detailId/:detailId/detailName/:detailName",
views: {
'main@': {
templateUrl: function ($stateParams){
//move this to a util function later
var tempName = unescape($stateParams.detailName);
tempName = tempName.replace(/\s/g, "-");
return '../partials/slides/' + tempName + '.html';
},
resolve: {
DetailData: ['DetailService', function(DetailService){
return DetailService.getDetails();
}]
},
controller: function ($stateParams) {
console.log( $stateParams.detailName + 'Ctrl');
return $stateParams.detailName + 'Ctrl';
}
}
}
})
控制器
.controller('NemtCtrl', ['$scope', '$rootScope', 'DetailData', function ($scope, $rootScope, detailData) {
console.log(detailData);
}]);
如果我删除功能,只需使用(控制台将记录detailData)控制器将工作
The controller will work if I remove the function and just use (console will log detailData)
controller: 'NemtCtrl'
但是,如果我这样做是行不通的:
But won't work if I do:
controller: function ($stateParams) {
return 'NemtCtrl';
}
我在做什么错在这里?有没有更好的方式来做到这一点?
What am I doing wrong here? Is there a better way to do this?
推荐答案
这是怎么发生的事情是,当你这样写:
What is happening here is that when you write this:
controller: 'NemtCtrl'
您告诉角度得到名为NemtCtrl控制器。但是,当你在另一方面这样写:
You tell angular to get the controller named 'NemtCtrl'. But when you on the other hand write this:
controller:
function ($stateParams) {
return 'NemtCtrl';
}
要定义这个状态的控制器。
you are defining a controller for that state.
更新
根据该UI的路由器文档做的方法如下:
According to the ui-router docs the way to do is as follows:
$stateProvider.state('contacts', {
template: ...,
controllerProvider: function($stateParams) {
var ctrlName = $stateParams.type + "Controller";
return ctrlName;
}
})
您可以阅读更多关于它在这里
You can read more about it here
更新2
有关你的情况会是这样:
For your case it would be something like:
.state("dashboard.item.detail", {
url: "/detailId/:detailId/detailName/:detailName",
views: {
'main@': {
templateUrl:
function ($stateParams){
//move this to a util function later
var tempName = unescape($stateParams.detailName);
tempName = tempName.replace(/\s/g, "-");
return '../partials/slides/' + tempName + '.html';
},
resolve: {
DetailData: ['DetailService',
function(DetailService){
return DetailService.getDetails();
}]
},
controllerProvider: //Change to controllerProvider instead of controller
function ($stateParams) {
//console.log( $stateParams.detailName + 'Ctrl');
return $stateParams.detailName + 'Ctrl';
}
}
}
})
这篇关于基于采用了棱角分明的UI路由器状态PARAMS负载控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!