AngularJS - UI Router stateChangeSuccess event not

2019-02-11 21:11发布

I am using UI Router in my angular app. I am trying to integrate state change events, but they are not firing on state change. Everything else is working fine and there is no error in console. I came across following similar questions, but none of the solution worked for me:

$rootScope.$on("$routeChangeSuccess) or $rootScope.$on("$stateChangeSuccess) does not work when using ui-router(AngularJS)

angular + ui-router: $stateChangeSuccess triggered on state b but not on a.b

Following is my Angular code:

(function() {

    angular.module("bootdemo", [
        "ngResource",       
        "ui.router",
        "bootdemo.core",
        "bootdemo.index"        
    ])
    .run(function ($rootScope, $location, $state, $stateParams) {

        $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){ 
            alert("root change success");
        })

        $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options){ 
            alert("root change start");
        })

        $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){ 
            alert("root change error");
        })
    })
    .config(function($stateProvider, $urlRouterProvider){
        $urlRouterProvider.otherwise('/');
        $stateProvider
            .state('index', {
                url: "/",
                templateUrl: '/index/templates/welcome.html',
                controller: 'IndexController as vm' 
            })
            .state('login', {
                url: "/login",
                templateUrl: '/index/templates/login.html',
                controller: 'LoginController as ctrl'   
            })
            .state('home', {
                url: "/home",
                templateUrl: '/index/templates/home.html',
                controller: 'HomeController as ctrl'    
        })
    });



}());

Left with no clue. I am not sure what I am missing.

3条回答
Anthone
2楼-- · 2019-02-11 21:52

If you are using the new ui-router (v1.0.0), the $stateChange* events will not work. You must use $transitions.on* hooks from now on.

You can read here.

https://ui-router.github.io/docs/latest/modules/ng1_state_events.html

https://github.com/angular-ui/ui-router/issues/2720

查看更多
Juvenile、少年°
3楼-- · 2019-02-11 22:05

StateChange events has been deprecated for ui.router >= 1.0

for the new ui.router use the following

StateChangeSuccess

$transitions.onSuccess({}, function() {
  console.log("statechange success");
});

StateChangeStart

$transitions.onStart({}, function(trans) {
 console.log("statechange start");
});

Check this migration guide for more information

查看更多
唯我独甜
4楼-- · 2019-02-11 22:14

$state events are deprecated for angular version > 1.0.0. now onward for change event we have to use $transitions

refer $transitions from here

查看更多
登录 后发表回答