AngularJS中$localStorage工作原理及使用方法技术咨询
Great question! Let's break this down clearly—first explaining how AngularJS's $localStorage works, then walking through a full usage guide with all the methods you asked about.
$localStorage 工作原理 First off, note that $localStorage isn't part of the core AngularJS library—it's provided by the third-party angular-local-storage module. It acts as a convenient wrapper around the browser's native localStorage API, making it play nicer with AngularJS's data binding system.
Here's the core breakdown:
- It persists data permanently in the browser (until manually cleared or the user wipes their browser cache).
- It automatically handles serialization/deserialization of complex data (like objects or arrays) so you don't have to manually use
JSON.stringify()orJSON.parse()like you do with nativelocalStorage. - It integrates with AngularJS's digest cycle, so changes to
$localStoragevalues will automatically update your views (if bound properly). - All data is stored as key-value pairs, tied to your app's domain (so other sites can't access it).
First, you'll need to set up the module:
- Include the
angular-local-storagescript in your project (via CDN, npm, or local file). - Inject it into your AngularJS app:
var myApp = angular.module('myApp', ['LocalStorageModule']); // Optional: Configure a prefix to avoid key collisions with other apps myApp.config(function(localStorageServiceProvider) { localStorageServiceProvider.setPrefix('myAppStorage'); });
Now let's cover each method you mentioned, with both native localStorage and AngularJS $localStorage examples:
1. 存储数据: localStorage.setItem() / AngularJS $localStorage
Native localStorage.setItem()
Stores a key-value pair, but only accepts strings. For complex data, you have to serialize it manually:
// Store a string localStorage.setItem('username', 'vivek_k'); // Store an object (requires manual serialization) const userProfile = { name: 'Vivek', role: 'Developer' }; localStorage.setItem('user', JSON.stringify(userProfile));
AngularJS $localStorage Approach
Much cleaner—no manual serialization needed. You can either use the set() method or directly assign values to the storage object:
myApp.controller('StorageController', function($scope, localStorageService) { // Option 1: Directly bind to the storage object (great for two-way binding) $scope.appStorage = localStorageService.getStorage(); $scope.appStorage.username = 'vivek_k'; $scope.appStorage.userProfile = { name: 'Vivek', role: 'Developer' }; // Option 2: Use the set() method localStorageService.set('theme', 'dark'); });
2. 获取数据: localStorage.getItem() / AngularJS $localStorage
Native localStorage.getItem()
Retrieves a value by key. For complex data, you have to deserialize it manually:
// Get a string const username = localStorage.getItem('username'); // Get an object (requires manual deserialization) const userProfile = JSON.parse(localStorage.getItem('user')); console.log(userProfile.name); // Outputs "Vivek"
AngularJS $localStorage Approach
Automatically deserializes complex data. You can either access the storage object directly or use the get() method:
myApp.controller('StorageController', function($scope, localStorageService) { // Option 1: Direct access $scope.appStorage = localStorageService.getStorage(); const username = $scope.appStorage.username; // Option 2: Use the get() method const userProfile = localStorageService.get('userProfile'); const theme = localStorageService.get('theme'); });
3. 删除单个项: localStorage.removeItem() / AngularJS $localStorage
Native localStorage.removeItem()
Deletes a specific key-value pair by key:
localStorage.removeItem('username');
AngularJS $localStorage Approach
You can use the remove() method or directly delete the property from the storage object:
myApp.controller('StorageController', function($scope, localStorageService) { // Option 1: Use the remove() method localStorageService.remove('theme'); // Option 2: Delete the property directly $scope.appStorage = localStorageService.getStorage(); delete $scope.appStorage.username; });
4. 清除所有数据: localStorage.clear() / AngularJS $localStorage
Native localStorage.clear()
Wipes all localStorage data for your domain (not just your app's):
localStorage.clear();
AngularJS $localStorage Approach
Use clear() to wipe all data, or clearAll() (if you set a prefix) to only remove data with your app's prefix:
myApp.controller('StorageController', function(localStorageService) { // Wipe ALL localStorage data for the domain localStorageService.clear(); // If you set a prefix earlier, wipe only your app's data localStorageService.clearAll(); });
- Storage Limit: Most browsers allow ~5MB of localStorage data per domain.
- Sensitive Data: Never store passwords, tokens, or sensitive info—localStorage is plaintext and accessible via browser dev tools.
- Browser Support: Works in all modern browsers and IE8+.
内容的提问来源于stack exchange,提问作者Vivek K

