gpt4 book ai didi

javascript - 如何使用 AngularJS 将数据存储在本地存储中?

转载 作者:行者123 更新时间:2023-11-28 00:12:04 25 4
gpt4 key购买 nike

我想使用 AngularJS 将信息存储在本地存储中,但我无法让它工作。我想知道是否有人可以帮助我?

这是我的代码:

    angular.module('todo', [])

.controller('ToDoCtrl', ['$scope', function($scope, $http) {
$scope.grocerylist = [];
$scope.priority = 'normal';

$scope.addTask = function() {
if(event.keyCode == 13 && $scope.groceryName) {
$scope.grocerylist.push({"name": $scope.groceryName, "completed": false});
$scope.groceryName = "";
}
}

$scope.deleteGrocery = function(index) {
$scope.grocerylist.splice(index, 1);
}
}])

最佳答案

如果你想避免使用第 3 方组件,实际上只需将 $window 作为依赖项注入(inject)到你的 Controller /服务/等中,这将允许你访问 $window .localStorage$window.sessionStorage

对于您的示例(更改了一些细节):

angular.module('todo', [])

.controller('ToDoCtrl', ['$scope', '$window', function($scope, $http, $window) {
$scope.grocerylist = $window.localStorage.getItem('grocerylist') || [];
$scope.priority = 'normal';

$scope.addTask = function(event) {
if(event.keyCode == 13 && $scope.groceryName.length) {
$scope.grocerylist.push({"name": $scope.groceryName, "completed": false});
$scope.groceryName = "";
$window.localStorage.setItem('grocerylist', $scope.grocerylist);
}
}

$scope.deleteGrocery = function(index) {
$scope.grocerylist.splice(index, 1);
$window.localStorage.setItem('grocerylist', $scope.grocerylist);
}
}])

通常,将这些问题抽象到服务中是一个好主意,这样您就可以在不同的存储方法之间切换(例如 localStorage、sessionStorage、POST 到服务器),而无需更改 Controller 代码。

关于javascript - 如何使用 AngularJS 将数据存储在本地存储中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30795766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com