Ken
Ken

Reputation: 3141

Editing particular record from list with Firebase and Angular

I am trying to allow users to edit their records in Firebase by clicking on an edit button next to the particular record (a modal then displays the editable information). When I use the code below, the console log shows projectIndex = -1, which I think means that the record I'm looking for can't be found. Any suggestions on how to modify this code to access the correct record?

.controller('EditProjectCtrl',
  function ($stateParams, Projects, $modalInstance, Auth) {

    var editProject = this;

    if( Auth.$getAuth() === null ) {
      Auth.$authAnonymously({rememberMe: true}).then(init)
       .catch(function(error) {
         console.log('error');
     });
   }
   else {
     init(Auth.$getAuth());
   }

    function init(authData) {
     editProject.projects = Projects(authData.uid);
   }

   var projectId = $stateParams.projectId, projectIndex;
   console.log(projectId) // displays something like this: -JpntT-F7KQe1KlA69uk
   projectIndex = editProject.projects.$indexFor(projectId);
   console.log(projectIndex);
   editProject.project = editProject.projects[projectIndex];
// . . . 
})
.factory('Projects', function(Ref, $firebaseArray) {

  return function(uid) {
   return $firebaseArray(Ref.child('projects').child(uid));
  };
    })

For what it's worth, when I used the original code in this previous Stack Overflow question of mine, I was able edit records without a problem (I updated that code because it was causing authentication issues).

Upvotes: 1

Views: 245

Answers (1)

Ruben
Ruben

Reputation: 195

From the AngularFire documentation:

$getRecord(key)

Returns the record from the array for the given key. If the key is not found, returns null. This method utilizes $indexFor(key) to find the appropriate record.

I believe your service should have a retrieveRecord function to check if a record exist or not. This being said if you already have the record - doesn't that mean it already exist? in which case you should have a edit function in your factory and then call it from your controller with the appropriate parameters.

Also, remember that queries night need to be used with the $loaded() function because of asynchronicity.

Upvotes: 1

Related Questions