我试图找到一种方式,让AngularJS重新评估状态/表达式时,页面是重新加载通过浏览器的历史后退按钮。
例如,此示例正常运行,但如果选中复选框并从页面导航,然后通过历史返回返回,则表达式不会重新计算,即使选中复选框,也会输出“未选中”:
<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>发布于 2022-04-04 12:15:38
为什么不在控制器中添加一些$onInit逻辑以确保在加载控制器时有一个定义的状态?这将确保在启动时设置已知状态:
myApp.controller('myController', ['$scope', function($scope) {
this.$onInit = function() {
$scope.myCheckbox = false;
}
}]);如果数据需要持久化(这意味着复选框状态应该与用户在重新加载页面之前保留的状态相同),则可以使用某些客户端存储机制(如Web )创建并注入“service”,以保存和恢复$scope.myCheckbox的数据(以及任何其他需要持久累积导航的属性)。
这还可以确保您的逻辑得到尊重,不管浏览器的行为是什么,浏览器之间的行为可能有所不同。
// 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...
}
};
});https://stackoverflow.com/questions/71650059
复制相似问题