1
我已经创建了一个小应用程序将数据添加到列表并计算总数;不过,我想利用本地存储来防止丢失页面上的数据。这是我试图无济于事。任何见解都会很棒!如何使用LocalStorage与角
angular.module('list', [])
.controller('RecordCtrl', function($scope){
// Historical data
$scope.history = [];
// Default data (can be loaded from a database)
$scope.records = [
];
forEach(values in localStorage){
var newValue = JSON.parse(localStorage[values]);
$scope.records.push(newValue);
}
// Total prices
$scope.Totals = function() {
var priceTotal = 0;
angular.forEach($scope.records, function (record) {
priceTotal += (record.price * record.qty);
});
// Return aggregate data
return { price: priceTotal };
};
// Delete data
$scope.Delete = function (index) {
// Remove first/oldest element from history if it reaches maximum capacity of 10 records
if ($scope.history.length === 10)
$scope.history.shift();
// Add deleted record to historical records
$scope.history.push($scope.records[index]);
// Remove from main records (using index)
$scope.records.splice(index, 1);
};
// Reset new data model
$scope.Reset = function() {
$scope.newDescription = '';
$scope.newQty = 0;
$scope.newPrice = 0;
$scope.newComment = '';
};
$scope.Reset();
// Add new data
$scope.Add = function() {
// Do nothing if no state is entered (blank)
if (!$scope.newDescription)
return;
var newHardware = {
description: $scope.newDescription,
qty: $scope.newQty,
price: $scope.newPrice,
comment: $scope.newComment
};
localStorage.setItem("values" + localStorage.length, JSON.stringify(newHardware));
$scope.records.push(newHardware);
/*
// Add to main records
$scope.records.push({
description: $scope.newDescription ,
qty: $scope.newQty,
price: $scope.newPrice,
comment: $scope.newComment
});
*/
// See $Scope.Reset...
$scope.Reset();
};
// Undo action (delete)
$scope.Undo = function() {
// Add last/most recent historical record to the main records
$scope.records.push($scope.history[ $scope.history.length - 1 ]);
// Remove last/most recent historical record
$scope.history.pop();
};
});
什么变量做你想存储在localStorage? –
即时使用ng-repeat列出$ scope.records数组。 –
所以你想要在更改时存储'$ scope.records',并在页面加载时加载它,对吧? –