作为一个新用户,我在使用 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> </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 对象的 Quantity 字段,但即使我使用按钮从 ng-repeat 传递“item”元素(这似乎是正确的参考),我也看不到数据同步到火力基地。