【问题标题】:AngularJS - UI Router stateChangeSuccess event not firingAngularJS - UI 路由器 stateChangeSuccess 事件未触发
【发布时间】:2016-09-06 22:10:44
【问题描述】:

我在我的 Angular 应用程序中使用 UI Router。我正在尝试集成 state change 事件,但它们不会在状态更改时触发。其他一切工作正常,控制台中没有错误。我遇到了以下类似问题,但没有一个解决方案对我有用:

$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

以下是我的 Angular 代码:

(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'    
        })
    });



}());

毫无头绪地离开了。我不确定我错过了什么。

【问题讨论】:

  • 我的“alpha”版本有问题,如果你用这个,请降级
  • 砰!我遇到过同样的问题。谢谢@ThomasP1988

标签: angularjs angular-ui-router single-page-application


【解决方案1】:

ui.router >= 1.0 已弃用 StateChange 事件

对于新的ui.router,请使用以下内容

状态改变成功

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

状态改变开始

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

查看migration guide了解更多信息

【讨论】:

    【解决方案2】:

    如果您使用的是新的 ui-router (v1.0.0),$stateChange* 事件将不起作用。从现在开始你必须使用$transitions.on* 钩子。

    你可以在这里阅读。

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

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

    【讨论】:

      【解决方案3】:

      $state 事件对于 Angular 版本 > 1.0.0 已弃用。 现在开始更改事件,我们必须使用 $transitions

      从这里参考$transitions

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-13
        • 2011-12-28
        • 1970-01-01
        • 2014-08-29
        相关资源
        最近更新 更多