Leogoesger Leogoesger -4 years ago 89
AngularJS Question

How to read and update based on item $id in Firebase?

I cannot figure out how to read and update using Firebase based on id. In this case, I have a list of todos, I want to find the first item based its $id, and then change

comple
to true.

todos
-Ke0JWl9xy5sZvT55hfE
Complete: false
Created_at: 1488228401479
Description: "123"
Priority: "high"
-Ke0Ms_LnsO-TSwQZLcZaddclose
-Ke0MuWCLkX29XWYyPBM
-Ke0MwKOrjpDm9rj6L28
-Ke0NCmpM3_dTPtY9jVb


JS

(function() {
function Todo($firebaseArray) {
var ref = firebase.database().ref().child("todos");
var todos = $firebaseArray(ref);

Todo.todos = todos;
Todo.updateToDo = function(todo){
console.log(todos)

console.log(todos[todo['$id']])
};
return Todo;
}

angular
.module('blocitoff')
.factory('Todo', ['$firebaseArray', Todo]);
})();

Answer Source

I'd take a much simpler approach:

(function() {
  function Todo($firebaseArray) {
    var ref = firebase.database().ref().child("todos");
    var todos = $firebaseArray(ref);

    Todo.todos = todos;
    Todo.updateToDo = function(todo){
      ref.child(todo['$id']).update({ completed: true });
    };
    return Todo;
  }

  angular
    .module('blocitoff')
    .factory('Todo', ['$firebaseArray', Todo]);
})();

The update() call here uses the Firebase JavaScript SDK. But since AngularFire is built on top of that, they interoperate perfectly anyway.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download