I have a problem with a variable that is not updated to the function $scopewhen a state change event occurs, although I can see that the variable is updated in the event listener.
Here is the code:
angular.module('testapp')
.controller('AnotherCtrl',
['$scope', '$rootScope', '$state',
function ($scope, $rootScope, $state) {
'use strict';
console.log("Init prevState.");
var prevState = 'null_state';
$scope.state = prevState;
$rootScope.$on('$stateChangeError',
function (event, toState, toParams, fromState, fromParams, error) {
console.log("Error");
if (toState.name === 'anotherState') {
console.log("Old State:" + prevState);
prevState = fromState.name;
console.log("New State:" + prevState);
}
})
$rootScope.$on('$stateChangeSuccess',
function (event, toState, toParams, fromState, fromParams) {
console.log("Success");
if (toState.name === 'anotherState') {
console.log("Old State:" + prevState);
prevState = fromState.name;
console.log("New State:" + prevState);
}
})
$scope.goBack = function () {
console.log("goBack:" + prevState);
$state.transitionTo(prevState, {arg: 'Robert'});
};
}]);
Here is the HTML template:
<div>
<h1>Another view</h1>
<br>
<br>
State: <span ng-model="state">{{state}}</span>
<br>
<br>
<button ng-click="goBack()">Back</button>
</div>
Here is the console output:

Therefore, when I press the button on the button that calls the function goBack(), the variable prevStateis still 'null_state'.
Can someone explain what the problem is?
. , AFAICS, , . , @Khanh TO. , . (angular.module.run). , , /, prevState , goBack() prevState. prevState rootScope .