UI-Router state.go回调状态变化

fub*_*bbe 33 angularjs angular-ui-router

成功调用state.go时我需要回调,并设置我的警报消息.在调用state.go之后,当前消息被推送到数组.State.go调用控制器,包含警报消息的数组设置为空.

结果,不会显示警告消息.

控制器:

$scope.alerts = []; // empty array, initialized on startup
.....
// This could be any function
.success(function(data, status, headers, config, statusText){
     $state.go($state.current, {}, {reload : true});
     $scope.alerts.push({type : 'success', msg : status});
})
.error(function(error){
    console.log(error.message);
});
Run Code Online (Sandbox Code Playgroud)

Dar*_*ous 94

$state.go() 返回一个承诺.

所以做以下事情:

$state.go('wherever', {whenever: 'whatever'}).then(function() {
  // Get in a spaceship and fly to Jupiter, or whatever your callback does.
});
Run Code Online (Sandbox Code Playgroud)


Fro*_*yon 7

您可以使用状态更改侦听器.

 $rootScope
            .$on('$stateChangeSuccess',
                function (event, toState, toParams, fromState, fromParams) {
                    //show alert()
                });
Run Code Online (Sandbox Code Playgroud)

请参阅状态更改事件.

  • @Fuser97381 为什么使用 rootscope 很糟糕? (2认同)
  • @ Fuser97381虽然你所说的一般是正确的,但并不意味着全局变量总是很糟糕.我绝对认为在没有rootcope的情况下,这应该是一种更好的方法,但使用它对我来说似乎并不可怕:你正在尝试跨越上下文*做某事*. (2认同)