Copy a $firebaseObject and save it to a different location

后端 未结 2 433
不思量自难忘°
不思量自难忘° 2021-01-28 05:23

In my application i\'m getting an object from my firebase using $firebaseObject. The use has two options with this object, change it and save the changes in the object or change

2条回答
  •  情深已故
    2021-01-28 05:38

    Incredibly useful answer. Adding my own solution which is just an expansion on Frane and using Angularfire 2.3:

    End result:

    • Bind first object to DOM When saving first object, save same object to another node using the same key to allow for future cross-reference In theory, you can also insert fields if needed before saving to node #2

    The html:

    
    {{ data.field1 || "empty"  }}
    
    
    
    {{ data.field2 || "empty"  }}
    
    

    In the controller:

    var ref = firebase.database().ref().child(entries);
    var obj = $firebaseObject(ref);
    obj.$bindTo($scope, "data");
    
    
    function saveData(){
        $scope.data.$save().then(function() {
            var newObject = getObject($scope.data);
            // In theory, add other field here
            var ref2 = firebase.database().ref().child(otherNode).child($scope.data.$id);
            ref2.update(newObject);
        }).catch(function(error) {
            console.log('Error ' + error.message);
        });
    }
    
    function getObject(obj) {
        var newObj = {};
        for (var key in obj) {
            if (key.indexOf('$') < 0 && obj.hasOwnProperty(key)) {
                newObj[key] = obj[key];
            };
        }
        return newObj;
    }
    

提交回复
热议问题