I'm trying to find a way for AngularJS to re-evaluate the state/expressions when the page is reloaded via the browser's history back button.
For instance, this example runs fine normally, but if you check the checkbox and navigate away from the page, then return via history back, the expression is not re-evaluated and will output 'Not Checked' even when the checkbox is checked:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<input type="checkbox" ng-model="myCheckbox"/>
<p>{{myCheckbox ? 'Checked' : 'Not Checked'}}</p> <!-- Outputs 'Checked' normally, but if page is reloaded via history back, myCheckbox can be true yet this outputs 'Not Checked' -->
</div>
<script>
angular.module("myApp", []).controller("myController", function ($scope) {
});
</script>
CodePudding user response:
Why not adding some $onInit logic in your controller to ensure a defined state when the controller is loaded? This will ensure that a known state is set on startup:
myApp.controller('myController', ['$scope', function($scope) {
this.$onInit = function() {
$scope.myCheckbox = false;
}
}]);
If the data needs to be persistent (meaning that the checkbox state should be the same as it was left by the user before reloading the page) you can create and inject 'service' to save and restore the data for your $scope.myCheckbox (and any other properties that need to be persistent accross navigation) using some client-side storage mechanism like Web Storage Api.
This also ensures that your logic is respected no matter what the browser behavior is, which can differ from browser to browser.
// In your checkbox view, add an ng-change to track for user action
<input type="checkbox" ng-model="myCheckbox" ng-change="myCheckboxChange(myCheckbox)"/>
// in your controller define the handler for the checkbox change action
myApp.controller('myController', ['$scope', 'PersistentDataService', function($scope, PersistentDataService) {
this.$onInit = function() {
$scope.myCheckbox = PersistentDataService.get('myCheckbox');
};
$scope.myCheckboxChange = function(state) {
PersistentDataService = PersistentDataService.set('myCheckbox', state);
};
}]);
// in a new service, define the logic to store and retrieve data from the browser
myApp.service('PersistentDataService', function() {
return {
get: function(key) {
// logic to get data from Web Storage goes here...
},
set: function(key, value) {
// logic to set data in Web Storage goes here...
}
};
});