如何在AngularJS中针对特定路由设置/移除localStorage?
Got it, let's fix this up properly. Your current code sets the user localStorage item when the /user route loads, but it doesn't handle cleaning it up when the tab is closed. Here's a complete implementation that meets your requirements:
Step 1: Update the User Controller
We need to add two key things: a listener for the tab close/unload event, and cleanup when the user navigates away from the /user route within the app.
var app = angular.module('Test', ['ngResource', 'ngRoute']); app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider){ $locationProvider.hashPrefix(''); $routeProvider .when('/', { templateUrl: 'home.html' }) .when('/user', { templateUrl: 'user.html', controller: 'User' }) .otherwise({ redirectTo: '/' }); }]); app.controller('User', function($scope) { // Set localStorage when entering the /user route localStorage.setItem('user', "true"); // Function to remove the localStorage item function cleanUpUserStorage() { localStorage.removeItem('user'); } // Listen for tab close/refresh events window.addEventListener('beforeunload', cleanUpUserStorage); // Remove the listener when leaving the /user route (controller destroys) // This prevents accidental cleanup when navigating to other routes in the same tab $scope.$on('$destroy', function() { window.removeEventListener('beforeunload', cleanUpUserStorage); }); });
How This Works
- Route Entry: When the user navigates to
/user, the controller initializes and setslocalStorage.setItem('user', "true"), making this value available across the entire app. - Tab Close/Refresh: The
beforeunloadevent fires when the tab is closed, refreshed, or the user navigates to an external site—this triggerscleanUpUserStorage()to remove theuseritem. - Internal Route Navigation: When the user moves from
/userto another route in the same tab, the controller's$destroyevent fires, which removes thebeforeunloadlistener. This ensures we don't accidentally delete theuseritem if the user later closes the tab from a different route.
Important Note
Since localStorage is shared across all tabs for the same origin, closing one /user tab will remove the user value for all other tabs. If you need the user value to persist as long as any /user tab is open, consider using sessionStorage (which is tab-specific) instead, or add additional logic to track active tabs using the storage event.
内容的提问来源于stack exchange,提问作者its me

