问题
In my AngularJS (v. 1.5.x), I'm converting my controller-based states to component-based states with ui-router 1.0.0 (currently in beta 1).
I'm having troubles catching state changes, that where previously caught with $rootScope.on('$stateSuccess', ...
. As far as I can tell, I am doing what described in the docs, and in this SO question, therefore I am wondering if I am missing something or if this is a bug of the beta 1 release.
I have not converted all controllers yet, only few.
The converted ones look like this (based on info gotten from RFC: Routing to Angular 1.5 .component()):
.state('componentstate', {
url: '/myUrl',
component : 'myComponent'
});
Navigation to this states works fine.
To update my code to the new Transitions
logic, I'm changing this:
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
if($state.current.name == 'acontrollerbasedstate') // do stuff;
});
to this:
$transitions.onSuccess( { to: 'acontrollerbasedstate', from: '*' }, function() {
// I've also tried { to: '*', from: '*' }
console.log('running');
// do stuff
});
Since it was not working, I've also testes all methods:
$transitions.onBefore( { to: '*', from: '*' }, function() {
console.log('onBefore');
});
$transitions.onEnter( { to: '*', from: '*' }, function() {
console.log('onEnter');
});
$transitions.onError( { to: '*', from: '*' }, function() {
console.log('onError');
});
$transitions.onExit( { to: '*', from: '*' }, function() {
console.log('onExit');
});
$transitions.onFinish( { to: '*', from: '*' }, function() {
console.log('onFinish');
});
$transitions.onRetain( { to: '*', from: '*' }, function() {
console.log('onRetain');
});
$transitions.onStart( { to: '*', from: '*' }, function() {
console.log('onStart');
});
$transitions.onSuccess( { to: '*', from: '*' }, function() {
console.log('onSuccess');
});
Unfortunately nothing ever gets printed in the console, which means the callback function of $transitions.onSuccess
never gets executed.
//////
UPDATE
//////
I've tried without declaring to
or from
, and it works:
$transitions.onStart( {}, scrollToTop);
$transitions.onSuccess({}, function(){
// here I use $scope.current.name, which for my purposes, works fine for now
});
来源:https://stackoverflow.com/questions/39269260/ui-router-1-0-0-beta1-transitions-onsuccess-from-rootscope-onstatesuccess