来自firebase的数据未在路由更改时加载,但在刷新时会加载

时间:2014-03-03 18:37:22

标签: angularjs firebase angularfire

我正在使用angularFire和Angular来更新一些视图,但奇怪的是当我从视图切换到视图时数据没有加载,但是当我刷新页面时它会这样做。发生了什么事?

WizardController:

/* initialize data */

var ref = new Firebase('https://dlwj.firebaseio.com/');

/* set data to automatically update on change */

$scope.currentLocation = $route.current.$$route.originalPath;
$scope.propertyRef = $firebase(ref);

$scope.propertyRef.$on('loaded', function(value) {

  //value will be undefined when I switch views using hash routes.
  //there is no issue when I just refresh on that page.
  console.log(value); 
  $scope.propertyConfiguration = value.products;
  var products = [];
  for (var key in value.products) {
    if (value.products.hasOwnProperty(key)) {
      products.push(key);
    }
  }

  $scope.productsArray = products;

});

console.log('Data retrieved');

路线:

$routeProvider.when('/SharedProperties',
{
  templateUrl: 'partials/SharedPropertiesPartial.html',
  controller: 'WizardController'
});

$routeProvider.when('/Registration',
{
  templateUrl: 'partials/Registration.html',
  controller: 'WizardController'
});

$routeProvider.when('/Login',
{
  templateUrl: 'partials/Login.html',
  controller: 'WizardController'
});

1 个答案:

答案 0 :(得分:5)

没有理由使用像$ firebase这样的包装器来下载数据(它负责同步等),然后立即将数据拉出并将其放入不同的范围对象中。

只需声明你的范围var:

$scope.products = $firebase(ref);

使用它:

<ul>
   <li ng-repeat="product in products | orderByPriority">{{product|json}}</li>
</ul>

如果您需要在控制器或服务中迭代数据:

$scope.products = $firebase(ref);

// some time later, probably in $scope.products.$on('loaded')...
// note that $getIndex() is only useful here to get the keys in
// the order they appear in the database, otherwise, forEach($scope.products, ...)
// is sufficient
angular.forEach($scope.products.$getIndex(), function(key) {
   console.log(key, $scope.products[key]);
});

如果您想将Firebase用作静态数据库(对于像我这样的所有实时事物而言非常困惑)并且每次有更改时都不会收到通知,您只需执行以下操作:

angular.controller('MyController', function($timeout, $scope) {
   new Firebase('<URL>').once('value', function(snap) {
      $timeout(function() {
         $scope.products = snap.val();
      });
   });
});

然后正常使用它:

<ul>
   <li ng-repeat="(key,product) in products">{{key}}: {{product|json}}</li>
</ul>