【发布时间】:2014-10-03 00:51:16
【问题描述】:
我需要在每个控制器中从 firebase 获取一组 products,如果我不必每次都进行 API 调用,那将是理想的选择。使用 angularfire 库实现这一目标的最佳方法是什么?
https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebasearray
现在我有(在咖啡脚本中):
app = angular.module 'EApp', ['ui.router', 'firebase']
app.config ($stateProvider, $urlRouterProvider) ->
$stateProvider
.state 'catalog',
url: '/catalog'
templateUrl: 'partials/catalog.html'
controller: 'catalogCtrl'
.state 'product',
url: '/product/:id'
templateUrl: 'partials/product.html'
controller: 'productCtrl'
$urlRouterProvider.otherwise 'catalog'
return
app.controller 'catalogCtrl', ($scope, $rootScope, $firebase) ->
ref = new Firebase("https://my-url.firebaseIO.com/")
$scope.products = $firebase(ref).$asArray()
return
app.controller 'productCtrl', ($scope, $rootScope, $stateParams, $firebase) ->
ref = new Firebase("https://my-url.firebaseIO.com/")
$scope.products = $firebase(ref).$asArray()
return
有什么方法可以将两个控制器中的公共代码分解出来,并将products 设置为$rootScope(或类似)级别,这样我就可以在产品完成后在productCtrl 中执行_.find退了吗?
【问题讨论】:
-
创建一个服务,并在该服务中让您的数据变量以空值开始。在第一次 firebase 调用时,设置您的数据变量,然后在每次后续调用中检查 null,如果为 null,则再次从 firebase 检索,否则使用存储的内容。
标签: angularjs firebase angularfire