这是我第一次尝试使用本地存储在.NET中使用角度,而我仍然在尝试理解事物。我希望有人能在这里指导我。以下是我尝试做的一些代码片段。
这是client.html:
<div class="box-footer">
<button type="submit" class="btn btn-primary btn-sm" data-ng-click="vm.save()"> Save</button>
</div>
这是clientService.js:
// Suppose to combine SAVE and EDIT but how?
function save(client) {
var clients = [];
if (localStorage.getItem('clients') != null)
clients = JSON.parse(localStorage.getItem('clients'));
clients.push(client);
localStorage.setItem('clients', JSON.stringify(clients));
}
function edit(client) {
var clients = [];
if (localStorage.getItem('clients') != null)
clients = JSON.parse(localStorage.getItem('clients'));
clients.forEach(function (client) {
//compare the two ID's, if they are the same
//Update
});
//save
localStorage.setItem('clients', JSON.stringify(clients));
}
这是client.js:
var vm = this;
vm.client = {
id: '',
firstname: '',
lastname: '',
age: ''
};
function edit() {
clientService.edit(vm.client);
getClients();
clear();
}
function save() {
clientService.save(vm.client);
getClients();
clear();
}
我希望有一个保存按钮,可以在从表中选择后添加新数据并更新数据。
答案 0 :(得分:0)
您可以使用三元运算符在提交时检查是否有客户。
<button type="submit" class="btn btn-primary btn-sm" data-ng-click="vm.client ? vm.edit() : vm.save()">
答案 1 :(得分:0)
如果您希望更新或使用相同的功能保存,请尝试这样的事情
function edit(client) {
var clients = [];
var data = JSON.parse(localStorage.getItem('clients'));
if (data != null){
clients = data;
var position = data.indexOf(client);
/** checks if existing or not if then it will upadte same**/
if(position != -1){
clients[position] == client;
}
else{
clients.push(client)
}
}
else {
/** push first item**/
clients.push(client)
}
clients.forEach(function (client) {
//compare the two ID's, if they are the same
//Update
});
//save
localStorage.setItem('clients', JSON.stringify(clients));
}