在Angular中有一个切换功能可以按预期工作,但是当页面刷新时,切换状态不会持续
目标:在页面刷新时维持切换状态
$scope.toggle = !$scope.toggle;
$scope.$watch('toggle', function(){
$scope.toggleText = $scope.toggle ? 'Guess The Year!' : 'Reveal The Year';
})
//HTML
<div> ng-show="toggle">Reveal </div>
<div> ng-hide="toggle">Hide </div>
答案 0 :(得分:1)
我认为您应该使用本地存储来解决此问题
以下是一些可以帮助您的代码
().controller('asdad', [function() {
//default setting
$scope.toggle = localStorage.toggle !== undefined ? JSON.parse(localStorage.toggle) : YourDefaultValue;
//change state function
$scope.stateFun = function() {
$scope.toggle = !$scope.toggle;
$scope.$watch('toggle', function(){
localStorage.toggle = $scope.toggle;
$scope.toggleText = $scope.toggle ? 'Guess The Year!' : 'Reveal The Year';
})
};
}]);
答案 1 :(得分:-1)
在刷新页面时,再次调用控制器,因此所有范围变量也会再次初始化。 如果您想在localStorage中维持其值位值。