gpt4 book ai didi

javascript - AngularJS 在运行函数中访问 $stateParams

转载 作者:行者123 更新时间:2023-12-04 02:01:36 26 4
gpt4 key购买 nike

我希望能够在我的 run 函数中访问 url 参数,并根据这些参数执行操作。但是,我很惊讶地看到 ui.router 的 $stateParams 对象在我的运行函数中是空的。

angular.module('app', ['ui.router'])
.run(['$rootScope', '$state', '$stateParams', '$location', function($rootScope, $state, $stateParams, $location) {
$rootScope.$state = $state;
$rootScope.location = $location;
$rootScope.$stateParams = $stateParams;
$rootScope.$on('$stateChangeStart', function(event, toState) {
if (toState.name === 'main') {
event.preventDefault();
$state.go('main.child', {

param: 1

})
}
});
console.log('$stateParams is empty!');
console.log($stateParams);
console.log($rootScope.$stateParams);
}])
.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {

$stateProvider
.state('main', {

url: '',
template: '<div>hey</div><div ui-view></div>'

})
.state('main.child', {

url: '/:param',
template: 'child state template'


});
}]);

是否可以在 run 函数中访问从 $stateParams 访问的参数?或者它们只在 config 函数中可用?为什么它们不能在 run 函数中访问?

请联系:http://plnkr.co/edit/1YXKRmR48LyxbGXWq66Y?p=preview

感谢您的帮助。

最佳答案

看起来您正在使用 StateChangeStart 事件并且您可以访问此事件中的参数:

 $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
//you code goes here
console.log(toParams);
}

我正在使用它向参数(身份验证重定向)添加一些自定义逻辑

关于javascript - AngularJS 在运行函数中访问 $stateParams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32302411/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com