Search code examples
angularjsangularjs-scopefirebaseangularfirefirebasesimplelogin

How to edit object in array using Firebase + Angular


In my Firebase + Angular (with AngularFire) app I have an array of objects which are formatted as a table with ng-repeat. Each row is a different object.

I want to add option to "assign" particular object to a user who is currently logged in with Firebase Simple Login. I added function assignTo(item) similar to deleteItem(item) but that doesn't work for me.

What am I doing wrong?

<div ng-controller="itemsCtrl">
  <table>
    <tr ng-repeat="item in items">
    <!-- table row aka object starts here -->
    <td>
      {{ item.assignedTo}}
    </td>
    <td>
      <form ng-submit="assignTo(item)">
       <button ng-click="items.$save(item)"class="btn btn-default">Assign</button>
      </form>               
        </td>
        <td>
          <form ng-submit="deleteItem(item)">
        <button ng-click="items.$remove(item)">Remove</button>
        </form>
      </td>
    </tr>
  </table>
</form>
<!-- table row aka object ends here -->
...
</div>

and here's my controller

app.controller("itemsCtrl", ["$scope", '$rootScope', "$firebase", "simpleLogin",
   function($scope, $rootScope, $firebase, simpleLogin) {
     var ref = new Firebase("https://--------.firebaseio.com/");
     $scope.items = [];
     var sync = $firebase(ref);
     $scope.items = sync.$asArray();
     $rootScope.auth = simpleLogin;

    ...

     $scope.assignTo = function(assignedTo) {
       $scope.items[i].assignedTo = $rootScope.auth.user.displayName;
       $scope.items[i].$save(i)
     };
   }
 ]);

UPDATE: this solved the problem

<tr ng-repeat="(key, item) in items">
...
<td>
<button ng-click="assignTo(key)" class="btn btn-default">Assign</button>
</td>

and

 $scope.assignTo = function(key) {
   console.log($scope.items[key].assignedTo);
   $scope.items[key].assignedTo = $rootScope.auth.user.displayName;;
   $scope.items.$save(key);
 };

Solution

  • Since you are working with arrays here, using (key, item) isn't ideal (this is a construct for iterating objects).

    Angular provides the special $index variable which represents i in your example above:

    <button ng-click="assignTo($index)">Assign</button>
    

    Also, you already have the item when you make the call, so there is no need to look it up by key or index ($save will also accept the actual item in place of the index ):

    <tr ng-repeat="item in items">
      <td>
        <button ng-click="assignTo(item)">Assign</button>
      </td>
    
    $scope.assignTo = function(item) {
       item.assignedTo = $rootScope.auth.user.displayName;;
       $scope.items.$save(item);
     };