【发布时间】:2026-01-09 09:40:02
【问题描述】:
我正在尝试在需要 $stateParams 的子状态中初始化一些变量。
为此,我使用以下方法注册了状态:
$stateProvider
.state('parent', {
abstract: true,
url: '/parent',
template: '<div ui-view></div>',
controller: 'ParentCtrl',
}).state('parent.child', {
url: '/:id',
templateUrl: 'template.html',
controller: function ($scope) {
$scope.someFunction();
},
});
这是我的控制器:
module.controller('ParentCtrl', [
'$scope', '$stateParams',
function ($scope, $stateParams) {
//calling a function in the scope inherited from parent controller
$scope.someFunction = function () {
//$stateParams isn't available.
}
}]);
但是当调用 someFunction 时,$stateParams 中的参数是未定义的。
但是,如果我不是从 ParentCtrl 调用函数,而是像这样从状态控制器内部运行:
$stateProvider
.state('parent', {
abstract: true,
url: '/parent',
template: '<div ui-view></div>',
controller: 'ParentCtrl',
})
.state('parent.child', {
url: '/:id',
templateUrl: 'template.html',
controller: function ($scope, $stateParams) {
//$stateParams is available
},
});
我可以访问 $stateParams 上的参数。
谁能解释一下为什么?
【问题讨论】:
-
@RadimKöhler 也许我错过了一些东西,但 $stateParams 与 $scope 继承有何关系?因为我怀疑子控制器调用的函数在 $stateParams 填充参数之前运行的事实。但我可以在同一个子控制器中使用参数。
-
您是否尝试访问父路由。正如SO post 中所述,您可以在父控制器或解析中获取 $stateParams。我created a plunkr 将其扩展为包含父控制器 - here,其中您可以毫无问题地访问父控制器中的 stateParams。你忽略了一些东西。
标签: angularjs angular-ui-router