How to delete data from Firebase? - javascript

I'm working with Firebase and AngularJS and I need to delete random generated id in Realtime Database.
var todoFirebaseID;
//add Firebase
$scope.addFirebase = function() {
var objects = {
title: objectTitle.value,
content: objectContent.value
}
var list = $firebaseArray(storageRef);
list.$add(objects).then(function(storageRef) {
todoFirebaseID = storageRef.key;
$scope.addTodo();
});
}
// Remove Firebase
$scope.removeFirebase = function() {
var obj = $firebaseObject(storageRef);
obj.$remove().then(function() {
});
}
I tried it, but it deletes all data in Firebase. I need to delete only the selected data.
Does anyone know how to do it?

You're telling Firebase to remove the entire database, so that's precisely what it does. If you only want to remove a single item, you should invoke $remove() on that specific item.
The only way that I can see deleting an item from the code you shared is:
$scope.removeFirebase = function() {
var obj = $firebaseObject(storageRef.child(todoFirebaseID));
obj.$remove();
}
So we're passing in a reference to the todoFirebaseID child item.
In a more realistic app, you'd trigger a handler when the user clicks the delete button and then that handler would figure out the ID of the item the user clicked on.

Related

How to rerender Fullcalendar events

I've been trying for days to filter my fullcalendar and it still doesn't work properly. I've managed now at least to have 2 different calendars based on the page you are on (homepage or a different one with different events). So on the second one I have 2 dropdowns with lists. I've managed to pick the id of the selected item from the dropdown and I'm trying to give it as a parameter to my axios function so that the fullcalendar events has the json that I want. However if you change the type of the event (I have location as a type) then it doesn't update the change. So basically it initializes fine with the right events but if you have 2 types and want to change them from the dropdown it doens't do anything.
Here is the axios function:
events: async function () {
if (window.location.href.startsWith(window.origin + "/Booking")) {
var data = await axios.get("/Booking/GetBookingsFiltered/", {
params: {
locationIDparam: locationSelected(), // doesn't update when you change it
carIDparam: carSelected(),
}
})
//calendar.events = data.data; some things I've tried and don't work
//calendar.rerenderEvents();
//calendar.render();
return data.data;
} else {
var data = await axios.get("/Booking/GetBookingsByUser/") // this works
return data.data;
}
}
In case you need the code for how I get the parameters:
function locationSelected() {
var location = document.getElementById("location_filter");
var selected_location = location.options[location.selectedIndex].value;
console.log("You selected location: " + selected_location);
return selected_location;
//$("#calendar").fullCalendar('renderEvent');
//$('#calendar').fullCalendar('rerenderEvents');
}
function carSelected() {
var car = document.getElementById("car_filter");
var selected_car = car.options[car.selectedIndex].value;
console.log("You selected car: " + selected_car);
return selected_car;
}
I've tried using $("#calendar").fullCalendar('renderEvent');, $("#calendar").fullCalendar('rerenderEvent'); $("#calendar").fullCalendar().render(); idk nothing I find online or in the documentation of fullcalendar work....please help

List refresh after delete in Angularjs

I am learning angularjs.I have created one order List and have delete button in every row. My delete function is working fine,what i need to do to refresh the list after delete success.
this below is my sample code
$scope.deleteFunc = function (id) {
var deleteOrder = $resource('/api/orders/:id', { id: id });
deleteOrder.delete();
Order = $resource("/api/orders")
$scope.Order = Order.query();
};
})
Please suggest the proper way how to refresh the list.
Angular resource requests are asynchronous. So when you do deleteOrder.delete(), the request need time to execute.
So when you do Order.query(), the request of the delete may still be in progress. So your server just give your order again in your list.
You must refresh the list after the end of the delete request.
$scope.deleteFunc = function (id) {
var deleteOrder = $resource('/api/orders/:id', { id: id });
deleteOrder.delete(function() {
// This function will be called at the end of the delete
Order = $resource("/api/orders")
$scope.Order = Order.query();
});
};

$firebaseArray losing functions after saving a child element

I am trying to implement a list-details view. The list is generated with $firebaseArray(ref). When an item on the list is clicked, the list controller uses list.$getRecord(item.$id) to get the particular record. Puts it in a global service(just and empty object with set and get) and in my detail controller i assign that service(already set to the selected item) to a scope variable in the detail controller and display it.
The information in the detail view is editable. and when it is editted, a save button appears which when clicked saves the edit using this code
item = editItem; //editItem contains the new changes made on the detail page
list.$save(item).then(function(ref){
//ref.key() === item.$id; //
console.log("Your Edit has been saved');
});
This works. The edits are reflected on the remote firebase data.
But the problem occurs when i navigate back to the list view and try to click another item. It gets an error which says list.$getRecord() is not a function. Now this error doesn't occur when you don't save an edit on the details view.
I printed out the list array before and after i save and i realised this
List array before an item is saved (contains AngularFire methods)
List array after an item is saved (no longer contains AngularFire methods)
I have no idea why $firebaseArray is reacting this way. Is there something i am missing? is this a normal behaviour?
PS: i am using ionic and angularFire.
I can post more code if neccesary
EDIT
Here is an abstraction of the code
List.html
<ion-list>
<ion-item href="#/lead/info" ng-click="vm.selectItem(l.$id)" ng-repeat="l in vm.list" >
<h3>{{l.firstName}} {{l.lastName}}</h3>
<h4 class="">
<p>{{l.topic}}</p>
</h4>
</ion-item>
</ion-list>
list.js (controller function)
function ListCtrl(selectedItem, $firebaseArray) {
/* jshint validthis: true */
var vm = this;
vm.list= {};
vm.selectItem = selectItem;
loadList(); //Loads the List array
function loadList() {
var fireList = new Firebase("https://xxxxx.firebaseio.com/list");
var r = $firebaseArray(fireList);
r.$loaded(function () {
vm.list = r;
});
console.log(vm.list); //Outputs the first image(above). But after an item edit and i go back, outputs the second image(above)
}
function selectItem(index) {
var sItem = vm.list.$getRecord(index);
selectedItem.setList(vm.list);
selectedItem.setItem(sItem);
}
}
The selectedItem service is simple. i use it to set a single object or array of objects
function selectedItem() {
var sItem = {};
var List = {};
return {
getItem: function () {
return sItem;
},
setItem: function (authObject) {
sItem = authObject;
},
getList: function(){
return List;
},
setList: function(al){
List = al;
}
};
};
The detail view controller is ass so:
item.js(controller function)
function ItemCtrl(selectedItem, $scope, $firebaseObject) {
/* jshint validthis: true */
var vm = this;
$scope.selectedItem = selectedItem.getItem();
$scope.listArray = selectedItem.getList();
//vm.item = $scope.selectedItem;
function saveEdit() {
var t = $scope.selectedItem;
$scope.listArray.$save(t).then(function(ref){
//console.log(ref);
});
}
};
UPDATE
After serious cross checking throughout my code i realised the issue is not from AngularFiire array. Even the workaround i did with the r.$watch and r.$loaded was unnecessary. the need for the work around was cause by another part of my code i didnt think was relevant.
I apologise for the mistake. I'd be deleting this question and a related one soon
Try using a watcher to reload the data:
var fireList = new Firebase("https://xxxxx.firebaseio.com/list");
var r = $firebaseArray(fireList);
r.$watch(function() {
r.$loaded(function () {
vm.list = r;
});
});
This is a common way of dealing with updates in an easy way, might solve your problem.

Firebase data gets overwritten ! sought guidance

I am building an Angular App with Firebase.
My intention is to create an object (say Rooms) at the root with 3 child objects (say Room1, Room2 & Room3) . Also, I am trying to create a logic that would check if the Rooms object is there - it wont create it again.
My code was :
var ref = new Firebase(firebaseURL);
ref.child('Rooms').once('value', function (snapshot){
if(snapshot.numChildren() == 0){
// Create Room within a loop
ref.child('Rooms').child(i).set(roomObj);
}else if(snapshot.numChildren() > 0){
// do not create
}
}
But when the code runs - it always enters into the if block !! And creates the child Rooms.
What is my mistake in the code ??
Most likely the value event will be triggered again with the value you expect.
Your solution is to run the code in a transaction.
var ref = new Firebase(firebaseURL);
ref.child('Rooms').transaction(function (data){
if(!data){
var rooms = {};
for (var roomNum=0; roomNum < 3; roomNum++) {
rooms['room'+roomNum] = { name: 'Room '+roomNum };
}
return rooms
}
}
So if the rooms don't exist yet, the above code creates them. If they already exist, the code does nothing (not returning a value, leaves the data unmodified).
Be sure to read the Firebase documentation for transaction.

Cant get the current id of a data from local Storage using jquery

I am working on an app to store data offline. My problem is when I try to retrieve the data from local storage for update/edit, it keeps calling only the id of the first item, and not calling the id of the data in view.
Please what am I doing wrong?
Here is my code for loading employees:
// load cases from localStorage
var employees;
if (localStorage.getItem('employees')) {
employees = JSON.parse(localStorage.getItem('employees'));
} else {
// If no cases, create and save them
employees = [];
// offling storing of our cases
localStorage.setItem('employees', JSON.stringify(employees));
}
// show case listing in list view page
var showEmployees = function () {
//erase existing content
$('#employee_list').html('');
//insert each employee
for (var i = 0; i<employees.length; i++) {
addEmployees(employees[i]);
}
};
Here is my code to add an employee to list view:
//add an eliment to list view
var addEmployees = function (empData) {
//HTML content of one list element
var listElementHTML = '<li><a class="employee_list" ui-btn ui-btn-e ui-btn-icon-right ui-icon-carat-r" data-transition="fade" data-split-icon="delete" href="#item'+empData.id+'">' + empData.employeename + '<br> ' + empData.dateofbirth + '</br></a></li>';
//appending the HTML code to list view
$('#employee_list').append(listElementHTML);
};
Here is my code for Edit function:
//User input to edit form
$('#edit_employee_page').on('click' , function () {
var editEmployee = JSON.stringify({
id: employees.length+1,
employeeno: $('#employeeno').val(),
employeename:$('#employeename').val(),
stateoforigine:$('#stateoforigine').val(),
employeephone: $('#employeephone').val(),
dateofbirth:$('#dateofbirth').val()
});
//Alter the slected data
localStorage.setItem("employees", JSON.stringify(employees));
return true;
});
for (var i in employees) {
var id = JSON.parse(localStorage.getItem(employees[i]));
}
Here is my code for the Edit button:
//register Edit button
$('.edit_button').live('click', function (e) {
alert('I was Cliked!');
e.stopPropagation();
$.each(employees, function(a, b) {
//if(b.id == employees[i]){
$('#id').val(b.id);
$('#employeeno').val(b.employeeno);
$('#employeename').val(b.employeename);
$("#stateoforigine").val(i.stateoforigine);
$('#employeephone').val(b.employeephone);
$('#dateofbirth').val(b.dateofbirth);
$("#id").attr("readonly","readonly");
$('#employeeno').focus();
$.mobile.changePage('#edit_employee_page');
return false;
//}
});
});
Here is my local Storage:
[
{"id":1,
"employeeno":"DEF/234/20014",
"employeename":"Bill Gates",
"stateoforigine":"Osun",
"employeephone":"080765432",
"dateofbirth":"12/11/1965"},
{"id":2,
"employeeno":"DEF/234/20014",
"employeename":"Bill Gates",
"stateoforigine":"Osun",
"employeephone":"080765432",
"dateofbirth":"12/11/1966"},
{"id":3,
"employeeno":"DEF/234/20014",
"employeename":"Bill Gates",
"stateoforigine":"Osun",
"employeephone":"080765432",
"dateofbirth":"12/11/1966"},
{"id":4,
"employeeno":"DAST/003/2003",
"employeename":"Gold Base",
"stateoforigine":"",
"employeephone":"",
"dateofbirth":"12/03/1986"}
]
Thanks for helping me out
The way you are storing your employees into localStorage is correct, but the way you are getting them out is incorrect. You stored your employees by stating:
localStorage.setItem("employees", JSON.stringify(employees));
So, in order to retrieve them, you must use:
var employees = JSON.parse(localStorage.getItem("employees"));
You see, you stored the data as a string with a key of "employees"; therefore, you can only retrieve it by that key. Since all data stored in localStorage is saved as a string, you must use JSON.parse() to convert the data back into an object - an array in this case. Then you can iterate over your employees.
Update:
You should be running this code as soon as the page is rendered (see below). I'm not sure how you're doing that - if you're using an IIFE or jQuery's document.ready() function. I don't think it's necessary to store an empty array into localStorage if none were loaded initially, so, I took your else clause out.
var employees = [];
if (localStorage.getItem('employees') !== null) {
employees = JSON.parse(localStorage.getItem('employees'));
}
Debug this line-by-line when it runs and make positive your employees variable contains data. If it doesn't contain data, well then, there's nothing to edit.
If, however, there is data, then execute your showEmployees() function. Oddly, I'm not seeing in your code where you actually call this. Is it bound to a button or action in your UI? Also, what is that for loop doing after your $('#edit_employee_page') click event function? It's trying to read data from localStorage improperly and it does nothing.
I think if you simply stepped through your code one line at a time using breakpoints and desk-checking your inputs/outputs you'd find out where you're going wrong.
It also appears that there's a disconnect in your code. May be you left out some lines; you define a string editEmployee but out of the blues you store JSON.stringify(employees) whereas employees is not defined in your code:
$('#edit_employee_page').on('click' , function(){
var editEmployee = JSON.stringify({
id: employees.length+1,
//........
});
//Alter the slected data
localStorage.setItem("employees", JSON.stringify(employees));
return true;
});
I had a similar task to do . I did it this way.
I passed the dynamic Id to be passed as an id attribute
id="'+empData.id+'"
and then inside the
$('.edit_button').live('click', function (e) {
alert('I was Cliked!');
var empId=$(this).attr('id');
rest of the code is same.

Categories

Resources