[英]Load Controller based on state params using Angular ui-router
I am trying to load a controller based on a stateparam to make it reusable 我正在尝试加载基于stateparam的控制器,以使其可重用
.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 调节器
.controller('NemtCtrl', ['$scope', '$rootScope', 'DetailData', function ($scope, $rootScope, detailData) {
console.log(detailData);
}]);
The controller will work if I remove the function and just use (console will log detailData) 如果我删除该功能并且只是使用(控制台将记录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'
You tell angular to get the controller named 'NemtCtrl'. 你告诉angular获得名为'NemtCtrl'的控制器。 But when you on the other hand write this:
但是当你另一方面写下这个:
controller:
function ($stateParams) {
return 'NemtCtrl';
}
you are defining a controller for that state. 你正在为那个州定义一个控制器。
Update 更新
According to the ui-router docs the way to do is as follows: 根据ui-router文档,方法如下:
$stateProvider.state('contacts', {
template: ...,
controllerProvider: function($stateParams) {
var ctrlName = $stateParams.type + "Controller";
return ctrlName;
}
})
You can read more about it here 你可以在这里阅读更多相关信息
Update 2 更新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';
}
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.