3

I have these function in one controller. I successfully imported the data, but I cannot use $add, $remove and $edit. I Use $RootScope because the items that are saved are in different state and hence different controller. I am new at this so I would really appreciate the help.

angular
    .module("")
    .factory("Factory",function($http,$firebaseArray){

        var ref = new Firebase('https://****.firebaseio.com/');

                return{
                ref:$firebaseArray(ref)
        }
    });

           $scope.saveItems = function() {
            console.log($scope.item);
            $rootScope.items.push($scope.item);

            $scope.item = [];
            $mdSidenav('right').close();
        }

        $rootScope.removeItems = function(item) { 
        var  index = $rootScope.items.indexOf(item);
        $rootScope.items.splice(index, 1);     
        };

            $rootScope.editItems=function(item){
            $rootScope.editing = true;
            $mdSidenav('right').open();
            $rootScope.item=item;

             $rootScope.saveEdit=function(){
              $rootScope.editing=false;

                $mdSidenav('right').close();
            };
        };

1 Answer 1

3

Arrays in Firebase can be kind of tricky. There is a good post from the Firebase blog that gets into the details a bit. But the biggest thing to understand is that the Arrays are actually stored as objects (which can make accessing by index tricky) and it is possible for multiple clients to update an array at the same time which can lead to unexpected results.

In your case, I think it is helpful to think about the data flow of what is going through your app. The beauty of the $firebaseArray is that whenever that array is updated on Firebase, the changes are broadcast to all connected clients.

In your application, rather than updating something on the $rootScope to see the changes reflected in your view, it makes more sense to update the data on Firebase and let $firebaseArray broadcast the changes. With the methods supplied with Firebase arrays you can actually do this directly in your view (see HTML section below).

// JavaScript
var app = angular.module("ItemApp", ["firebase"]);

app.controller("ItemCtrl", function($scope, $firebaseArray) {
    var itemsRef = new Firebase("https://xxxx.firebaseio.com/items");
    $scope.items = $firebaseArray(itemsRef);
  }
]);

And in the view:

//HTML example with remove only, can apply to add or edit
<ul>
  <li ng-repeat="item in items">
    {{ item.property }}
    <button ng-click="items.$remove(item)">x</button>
  </li>
</ul>

The big change here is to think not about updating your data on the client side and then trying to sync that back to Firebase, but rather to update the data on Firebase and then let the $firebaseArray sync out the changes to the client.

The docs on synchronized arrays have quite good detail on basic CRUD operations that you outlined above.