使用AngularJS,AngularFire和Firebase作爲新用戶,我遇到了分佈式代碼庫的問題。我試圖經常使用Factory()重用代碼並按照最佳實踐進行測試。但是,我無法將數據添加到我的AngularFire對象和Firebase。以編程方式將字段添加到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> </th>
<th> </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對象,但即使我從納克重複傳遞「項目」元素與按鈕,這似乎是適當的參考,我沒有看到數據同步到Firebase。
將'$ firebaseObject加載到'OneItem'中,然後修改'Item'上的字段。 'var OneItem = ItemData.OneItem(Item。$ id);'vs'Item.Description = OneItem.Description;'。修改'OneItem'上的屬性,然後調用'$ save()'。 –
@FrankvanPuffelen我用評論更新了代碼,以更好地解釋我正在嘗試做什麼。數據被標準化,並且每個商店可能具有與主項目列表不同的信息子集。 OneItem調用是爲Master項目的,所以我可以從中獲得描述,價格等等,用於我想要更新的工作列表。我不想更改主項目,但是商店項目。 –
就我所見,問題仍然存在:您需要在'$ firebaseObject'某處調用'$ save'來保存您的更改。如果不是這樣,你可以設置一個jsfiddle/jsbin來重現問題嗎? –