AngularJS Firebase无法在路线更改时预先加载数据

时间:2013-07-16 08:05:30

标签: angularjs firebase

 var testApp = angular.module('testApp', ['firebase'])
 .config(['$routeProvider','$locationProvider',function
     ($routeProvider,$locationProvider)
 {

 $routeProvider
  .when('/', {
    templateUrl: '/views/main.html',
    controller: 'MainCtrl'
  })
 .when('/test', {
    templateUrl: '/views/test.html',
    controller: testCrtl,
    resolve:
    {
        firedata: function($q,angularFire){
        var deffered = $q.defer();

        var ref = new Firebase('https://shadowfax.firebaseio.com/items');
        ref.on('value', function(result){
            deffered.resolve(result.val());
        });

        return deffered.promise;
        }

    }
  })
  .otherwise({
    redirectTo: '/'
  });
  // $locationProvider.html5Mode( true );
  }]);


angular.module('testApp')
.controller('MainCtrl', ['$scope','$routeParams','$rootScope', function ($scope,$routeParams,$rootScope) {

    $scope.load = function(){ return false;}
    $rootScope.$on('$routeChangeStart', function(next, current) { 
    $scope.load = function(){ return true;}

    });


}]);

 testApp.controller('TestCtrl',['$scope','$timeout','Fire','firedata','testCrtl']);

 var testCrtl = function ($scope,$timeout,Fire,firedata) {

            $scope.items=firedata;

 };

在上面的代码中,为什么$scope.items=firedata;的值为null?请解释如何执行类似Google的路由更改以预加载控制器的数据?这个例子就像John Lindquist解释的那样,但是当我使用Firebase的原生JS库时,我无法预先加载数据。

此外,使用Firebase angularFire库也无济于事,因为它使用$ scope作为参数,并且无法将$ scope传递给resolve函数。

1 个答案:

答案 0 :(得分:3)

您应该可以使用angularFireCollection来预加载数据:

.when('/test', {
  templateUrl: '/views/test.html',
  controller: testCrtl,
  resolve: {
    firedata: function(angularFireCollection){
      return angularFireCollection('https://shadowfax.firebaseio.com/items');
    }
  }
})