我有一个angularJs应用程序,需要对大多数页面进行身份验证。我已经实施了与http://www.frederiknakstad.com/2014/02/09/ui-router-in-angular-client-side-auth/
类似的检查在angular.module(' myModule')。run()中,我有:
$rootScope.$on('$stateChangeStart', function(event, toState, toParams){
if(toState.authenticate){
event.preventDefault();
var toUrl = $state.href(toState, toParams);
var promise = authService.isAuthenticated();
if (promise){
promise.then(function(){
// successful authentication proceed to requested state
$state.go(toState.name, toParams, {notify: false, inherit: false}).then(function(state){
$rootScope.$broadcast('$stateChangeSuccess', state.self, toParams);
});
},function(){
// failed authentication proceed to login
$state.go('login', {
next: toUrl
});
});
} else {
$state.go('login', {
next: toUrl
});
}
}
});
这工作得很好,但是,当我试图在表单变脏时阻止控制器内的状态更改时,它并不能正常工作。以下是我在控制器中添加监听器的方法:
$scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
if($scope.forms.myForm.$dirty) {
event.preventDefault();
modalAlert({
text: 'You have unsaved changes, are you sure you wish to continue'
}).result.then(function() {
// User is OK leaving dirty form, clear dirty flag to prevent this pop-up showing again and re-route
$scope.forms.myForm.$setPristine();
$state.go(toState, toParams);
}, function() {
// Cancelled request, stay on dirty form, don't need to do anything
});
}
});
基本上,正在发生的事情是,第一个$ stateChangeStart被调用,auth被解析,并且它将$ state.go()执行到我们要去的下一个状态。同时,模式弹出要求确认,如果我点击取消,它将恢复到之前的状态,但我的所有更改都消失了,因为身份验证检查已经改变了状态并丢失了所有更改。如果我要访问的页面不需要身份验证,那么它会按预期工作。
如何让控制器的$ stateChangeStart先执行?