您好,登錄后才能下訂單哦!
在AngularJS中管理本地存儲,您可以使用內置的$window.localStorage
對象
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
localStorageService
的服務,該服務將封裝對$window.localStorage
的操作:var app = angular.module('myApp', []);
app.service('localStorageService', function($window) {
this.setItem = function(key, value) {
$window.localStorage[key] = value;
};
this.getItem = function(key) {
return $window.localStorage[key];
};
this.removeItem = function(key) {
delete $window.localStorage[key];
};
this.clear = function() {
$window.localStorage.clear();
};
});
localStorageService
服務,并使用它來存儲、檢索、刪除和清除本地存儲數據:app.controller('myController', function($scope, localStorageService) {
// 設置本地存儲項
localStorageService.setItem('username', 'JohnDoe');
// 獲取本地存儲項
$scope.getUsername = function() {
return localStorageService.getItem('username');
};
// 刪除本地存儲項
$scope.removeUsername = function() {
localStorageService.removeItem('username');
};
// 清除本地存儲
$scope.clearLocalStorage = function() {
localStorageService.clear();
};
});
ng-click
指令調用函數以執行本地存儲操作:<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS LocalStorage Example</title>
</head>
<body ng-controller="myController">
<h1>AngularJS LocalStorage Example</h1>
<p>Username: {{getUsername()}}</p>
<button ng-click="removeUsername()">Remove Username</button>
<button ng-click="clearLocalStorage()">Clear Local Storage</button>
</body>
</html>
現在,您已經在AngularJS應用程序中成功管理了本地存儲。使用localStorageService
服務,您可以輕松地在應用程序中存儲、檢索、刪除和清除數據。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。