问题
Say I have
- a list view+controller that displays a list of item names and
- a detail view+controller thats shows detail for an item.
How would I use angularfire (preferably with automatic three way binding) in a way that does not fetch the same data twice?
Because controller#1 would have already fetched the items AND their details when the (itemsListRef).$bind($scope, 'items');
statement executes. In controller#2, (itemDetailRef,).$bind($scope, 'itemDetail')
would then fetch item detail data that again that has already been fetched in controller#1.
One option that comes to mind : An angular service could be used to fetch the items data once and then share the data between controllers, but I am not sure how angularfire three-way automatic binding would play into this, or if it would even work. Your thoughts/advise on this? Any other options? What would be the recommended way to handle this?
回答1:
The Firebase client is smart enough to use a local cache if it exists. Firebase instances are singletons for each base Firebase URL, so attaching multiple listeners at varying paths in the same Firebase will not result in unnecessary network activity.
I recommend creating a $firebase
reference in a service, and then using a 3-way data bind for the details of the item in a controller. For example:
var myapp = angular.module("myapp", ["firebase"]);
myapp.factory("ItemService", ["$firebase", function($firebase) {
return $firebase(itemsListRef);
}]);
myapp.controller("DetailCtrl", ["$scope", "ItemService", function($scope, items) {
items.$child(itemId).$bind($scope, 'itemDetail');
}]);
来源:https://stackoverflow.com/questions/21824796/how-to-optimise-data-retrieval-and-inter-controller-data-sharing-with-angularfir