I have a problem with a variable that is not updated to a $scope
function when a state change event occur even though I 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 () {
//$scope.state = 'anotherState';
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:
So when I press a button on the button which invokes the function goBack()
, the prevState
variable is still 'null_state'
.
Can anyone explain what the problem is?
UPDATE after review of the answers I have reviewed and tested all the suggested solutions. The core problem, AFAICS, had nothing to do with the string type being immutable. As I see It the best answer comes from @Khanh TO. The event listeners were not initialized when the controller was created in the first place. This was fixed with a bootstrapping (angular.module.run). Also the controller was re-initialized every time the state/view was loaded causing the variable prevState to be re-initialized, thus the listener functions and the goBack() function used different outer prevState variables. Storing the prevState on the rootScope solved this problem.