-->

how to make angularfire send ng-grid onBlur change

2019-06-10 11:03发布

问题:

This is a followup question from here: How to create 3 way data binding between angularFire 0.5.0 and latest ng-grid? where Kato nicely provided a solution:

var app = angular.module('app', ['firebase', 'ngGrid']);
var fb = new Firebase('https://nggrid-example.firebaseio-demo.com/');

app.controller('ctrl', function($firebase, $scope, orderByPriorityFilter) {
    $scope.data = $firebase(fb);
    $scope.myData = $firebase(fb);
    $scope.$watchCollection('data', function() {
       $scope.myData = orderByPriorityFilter($scope.data); 
    });
    $scope.gridOptions = { data: 'myData',enableCellEditOnFocus: true };
});

However, this solution puts data nicely into my ng-grid, but if I edit any of the cells, changes are not automatically applied to firebase.

I have tried various ways, but none of them seem to work :

$scope.$on('ngGridEventEndCellEdit',function(value){
                    $scope.data.$set(value);
                });

Nope.

I have also tried angularFire event handlers such as .$on("change")

Tables I am creating will be edited by multiple users in real time.

Kato solution nicely converts firebase objects into arrays, but then I also need to find a way how to convert edited values in ng-grid to objects so I can store them in firebase on the fly.

if I add ng-blur="updateEntity(col, row)" to my editableCellTemplate: and then I add this :

$scope.updateEntity = function(col,row){
                    console.log(row.entity);
                    console.log(col.field);
                };

console logs out perfectly, but I also get this error:

Error: Firebase.set failed: First argument contains an invalid key ($id) in property 'targetScope'. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"

P.S. I get this error only if I have this as well:

$scope.$on('ngGridEventEndCellEdit',function(value){
                    $scope.data.$set(value);
                });

If I dont have this piece, then nothing is being saved to firebase (or atleast tried).

回答1:

I finally found the solution !!

All that is needed to be done is adding this : ng-blur="updateEntity(col, row)" to editableCellTemplate: and then this:

$scope.updateEntity = function(col,row){
                    $scope.data.$save(row.entity.$id);
                };

Now this: $scope.data.$set(row.entity.$id); will not work, because it will replace THE WHOLE OF YOUR FIREBASE DATABASE with id (so a number, for example "0"). So always test it before using it! :)

Tadaaaa ! 3 way data binding!