javascript - 以编程方式将字段添加到 angularfire 并与 Firebase 同步

标签 javascript angularjs firebase angularfire firebase-realtime-database

使用 AngularJS、AngularFire 和 Firebase,作为新用户,我在分布式代码库方面遇到了问题。我尝试经常使用 Factory() 来重用代码并遵循测试的最佳实践。但是,我在向 AngularFire 对象和 Firebase 添加数据时遇到问题。

给定以下工厂:

angular.module('MyApp').factory("ItemData", ["$firebaseObject", "$firebaseArray", "GetFireBaseObject",
    function($firebaseObject, $firebaseArray, GetFireBaseObject) {
        var ItemsRef = GetFireBaseObject.DataURL('Items/');
        return {
            AllItems: function() {
                return $firebaseArray(ItemsRef);
            },
            OneItem: function(ItemKey) {
                var OneItemRef = ItemsRef.child(ItemKey); 
                return $firebaseObject(OneItemRef);
            }
        };
    }
]);

我可以获取我的项目,我可以处理数据等...但是,我似乎无法向对象添加元素,并将其添加到 Firebase。虽然当我调用 AddQuantity/MinusQuantity 时屏幕会更新数量,但我无法将此数据与 Firebase 链接并更新那里的记录。

angular.module('MyApp').controller('InventoryCtrl', ["$scope", "StoreData", "ItemData"
    function ($scope, StoreData, ItemData) {

        $scope.StoreList = StoresData.AllStores();
        $scope.SelectedStore = {};     // Store Information
        $scope.ItemList = {};          // Store Item List

        $scope.GetItemsForStore = function() {
            // StoreDate.OneStoreItems returns list of items in this store
            var ItemData = StoreItems.OneStoreItems($scope.SelectedStore.Key);  // $firebaseArray() returned

            for( var i = 0; i < ItemData.length; ++i)
            {
                var Item = ItemData[i];

                // Item Data is master item data (description, base price, ...)
                var OneItem = ItemsData.OneItem(Item.$id);  // Get Master by Key

                Item.Description = OneItem.Description;   // From Master
                Item.UnitPrice = OneItem.UnitPrice;
                Item.Quantity = 0;
                Item.UnitTotal = 0;
            }
            $scope.ItemList = ItemData;
        };

        $scope.AddQuantity = function(item) {
            if( ! item.Quantity ) {
                item.Quantity = 0;
            }
            ++item.Quantity;
        };

        $scope.MinusQuantity = function(item) {
            if( ! item.Quantity ) {
                item.Quantity = 0;
            }
            --item.Quantity;
            if(item.Quantity <= 0) {
                item.Quantity = 0;
            }
        };
    }
]);

HTML 片段

            <pre>{{ ItemList | json}}</pre>
            <div>
                <table class="table">
                    <thead>
                        <th>Product Code</th>
                        <th>Description</th>
                        <th>Qty</th>
                        <th>&nbsp;</th>
                        <th>&nbsp;</th>
                        <th>Extended</th>
                    </thead>
                    <tbody>
                        <tr ng-repeat="(Key, item) in ItemList">
                            <td>{{item.$id}}</td>
                            <td>{{item.Description}}</td>
                            <td>{{item.Quantity}}</td>
                            <td><button class="btn btn-success" ng-click="AddQuantity(item)">+</button></td>
                            <td><button class="btn btn-danger" ng-click="MinusQuantity(item)">-</button></td>
                            <td>{{item.UnitPrice | SLS_Currency}}</td>
                            <td>{{item.UnitTotal}}</td>
                        </tr>
                    </tbody>
                </table>
            </div>

我可以看到添加到元素中 ItemList 对象的 Quantity 字段,但即使我使用按钮从 ng-repeat 传递“item”元素(这似乎是正确的引用),我也没有看到数据同步到 Firebase。

最佳答案

我将工厂更改为服务,并且我相信这仍然可以通过工厂完成,但我必须添加 AngularFire 手册中的绑定(bind)功能,如图所示。下面的代码子集用于选择记录并进行添加。

angular.module('MyApp').service("ItemData", ["$firebaseObject", "$firebaseArray", "GetFireBaseObject",
    function($firebaseObject, $firebaseArray, GetFireBaseObject) {
        var ItemRef = GetFireBaseObject.DataURL('Items/');

        this.AddItem = function(Item) {
            var OneItemRef = ItemRef.child(Item.Key);
            OneItemRef.update(Item);
            return $firebaseObject(OneItemRef);
        };

        this.DeleteItem = function(ItemKey) {
            var OneItemRef = ItemRef.child(ItemKey);
            OneItemRef.remove();
        };      

        this.GetAllItems = function() {
            return $firebaseArray(ItemRef);
        };

        this.GetOneItem = function(ItemKey) {
            var OneItemRef = ItemRef.child(ItemKey);
            return $firebaseObject(OneItemRef);
        };
    }
]);

然后 Controller 必须执行添加的绑定(bind),这也可以在服务中完成:

angular.module('MyApp').controller('ItemCtrl', ["$scope", "ItemData", 
    function ($scope, ItemData) {

        $scope.Items = ItemData.GetAllItems();

        $scope.EditItem = function(Item) {
            var EditItem = ItemData.GetOneItem(Item.Key);
            // Bind here for real time updates - NOTE: Changes with each key
            EditItem.$bindTo($scope, "Item").then(
                function(unbind) {
                    $scope.ItemUnbind = unbind;
                }
            );
            $scope.Item.NewField = "ABC";     // Add extra field to Firebase
        };

        $scope.SaveItem = function(Item) {
            if( ! $scope.ItemEditMode )
            {
                $scope.Item = ItemData.AddItem(Item);
            }
        };
    }
]);

通过此更改,任何更改(例如每次按键)都将立即同步到 Firebase 数据中。

关于javascript - 以编程方式将字段添加到 angularfire 并与 Firebase 同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30446727/

相关文章:

javascript - 发送 ajax 请求并防止数据操纵的最安全的解决方案是什么?

javascript - 如何使用 AngularJS 过滤对象数组?

javascript - Chrome 上的原生日期选择器和 IE/Firefox 的回退

javascript - 更新状态,但不在 ReactJS 中重新渲染?

Javascript 动态调节

angularjs - 未找到 Angular 映射文件

javascript - 将 Firebase 可观察到的 Angular 映射到模板

firebase - 在 firebase 中,我可以设置权限以仅允许对给定对象执行 PUSH 操作吗?

ios - Firebase + Geofire 基于属性的复杂查询

javascript - 在 getscript 内部定义变量并在其外部使用它? (从 json 文件中获取头像并循环使用)