I'm encountering an issue where a variable isn't being updated in a $scope
function when there's a state change event. Despite seeing the variable update in the event listener, it doesn't reflect in the function.
The code snippet in question is as follows:
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 () {
//$scope.state = 'anotherState';
console.log("goBack:" + prevState);
$state.transitionTo(prevState, {arg: 'Robert'});
};
}]);
Below 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>
The console output shows that, even after pressing the button invoking the goBack()
function, the prevState
variable remains 'null_state'
.
If anyone could shed light on this issue, I would greatly appreciate it.
UPDATE following a review of the answers: After carefully reviewing and testing all proposed solutions, it appears that the core problem was not related to the immutability of string types. From my perspective, the most promising solution came from @Khanh TO. The issue stemmed from the event listeners not being initialized when the controller was first created, which was remedied by bootstrapping (angular.module.run). Another factor was that the controller was being re-initialized each time the state/view loaded, leading to the prevState variable also being re-initialized. Storing prevState on the rootScope resolved this conflict.