i am new with angular, have a aplication that manage some customers data, it is a json file that is stored in localStorage, how can i create partial update patch(delta) method in the service.
Also need a error handling.
json:
[
{"id":1,"name":"Gigi", "lastname":"DS", "hobby":"football", "age":"1987/06/04"},
{"id":2,"name":"John", "lastname":"Ciobanu", "hobby":"basball", "age":"2001/12/05"},
{"id":3,"name":"George", "lastname":"Doe", "hobby":"rugby", "age":"2003/05/09"},
{"id":4,"name":"Dean", "lastname":"Smith", "hobby":"tenis", "age":"2000/03/06"},
{"id":5,"name":"Kelly", "lastname":"Ambrose", "hobby":"sweem", "age":"1986/09/12"}
]
HTML:
<form name="part-update" novalidate>
<input type="number" class="number" name="id" value="{{customer.id}}" ng-model="customer.id" disabled />
<input type="text" name="name" value="{{customer.name}}" ng-model="customer.name" />
<input type="text" name="lastname" value="{{customer.lastname}}" ng-model="customer.lastname" />
<input type="text" name="hobby" value="{{customer.hobby}}" ng-model="customer.hobby" />
<input type="text" name="age" value="{{customer.age}}" ng-model="customer.age" />
<button class="btn btn-success btn-xs" ng-click="quickSave(customer)">save</button>
<button class="btn btn-danger btn-xs" ng-click="close()" >cancel</button>
</form>
Controller:
.......
$scope.quickSave=function(c){
customerData.quickUpdate(c);
$scope.quickEdit = false;
$scope.customer={};
refresh();
}
.......
service:
articleServices.factory("customerData",["$http",'LS','$q','$filter','$log',function($http,LS,$q,$filter,$log){
var baseUrl = 'jsondata/customers.json';
var dataLoad = null;
// throw('test');
init();
return{
............
//partial update
quickUpdate: function(c){
return dataLoad.then(function(data){
???????????????????
});
}
}
function init(){
customers = LS.getData("cutomers");
if(customers){
dataLoad = $q.resolve(customers);
}
else
dataLoad = $http.get(baseUrl).then(function(response){
LS.setData(response.data,"cutomers");
return response.data;
}).catch(function(e) { throw { status: e.staus, message: e.statusText }});
dataLoad.catch(onError);
return dataLoad;
}
function onError(error){
$log.error();
$log.error({ status: error.status, message: error.message, source: 'customerData'});
}
}]);
I found a solution for partial update
(angular.merge -> merge 2 objects)
var obj1 = {
'name': 'George',
'lastName': 'Doe'
}
var obj2 = {
'name': 'Gregor',
'age': '20'
}
var result = angular.merge({},obj1,obj2);
result={
'name': 'Gregor',
'lastName': 'Doe',
'age': '20'
}
For this particular case:
quickUpdate: function(c){
return dataLoad.then(function(data){
for(var i=0;i<data.length;i++){
if(data[i].id==c.id){
data[i] = angular.merge({},data[i],c);
break;
}
}
return data[i];
});
}
still need error handling :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With