【发布时间】:2015-08-31 09:36:01
【问题描述】:
我希望能够访问我的 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 函数中无法访问它们?
Plnkr:http://plnkr.co/edit/1YXKRmR48LyxbGXWq66Y?p=preview
感谢您的帮助。
【问题讨论】:
标签: javascript angularjs angular-ui-router