2

I have question regarding AngularJS. I want to make ng-repeat for some array. But data for this array i get from firebase in controller. Problem is, when page is rendering, iam still waiting for data from async function which get data from firebase.

What is the best way to control it? I tried to used promisses, but something was wrong and page was rendered before i got data from firebase.

i.e

$scope.games = [];
    function getOnce(){
        var defer = $q.defer();
        ref.once("value", function(data) {
            defer.resolve();
            $scope.games.push('test');
        });
        return defer.promise;
    }

    $scope.getdata = getOnce().then(function(data){
        console.log('success');
        console.log(data);

    });

And i call '$scope.getdata' function on init 'data-ng-init="getdata()"' What i wrong here? Or how can i get my goal?

3
  • this is how async/promises are supposed to work. The whole point of async is that other things can happen (like page rendering) while a server request is in progress. the code you posted here doesn't really show what your problem really is, though, because it doesn't seem to be using whatever data it is trying to get. Commented Oct 18, 2015 at 21:19
  • shouldn't be using ng-init just to trigger controller function, call it in controller. Also resolve isn't passing any data down the promise chain Commented Oct 18, 2015 at 21:20
  • Your getdata property is not a function, its a promise object. Commented Oct 18, 2015 at 21:21

2 Answers 2

2

Pass data in method resolve. In then populate the array with data response.

$scope.games = [];
    function getOnce(){
        var defer = $q.defer();
        ref.once("value", function(data) {
        defer.resolve('test');
    });
    return defer.promise;
}

$scope.getdata = getOnce().then(function(data){
    $scope.games.push(data);
    console.log('success');
    console.log(data);
});
Sign up to request clarification or add additional context in comments.

Comments

0

Well you could use an ng-show to just hide the parts of the page you don't want visible while you're loading the data. Or ng-if if your directives require that the data be loaded when their link/controller functions are ran by angular.

Does that suit your needs?


You'd need to expose whether or not you're done loading to the $scope with something like this:

$scope.isDoneLoading = false;
$scope.getdata = getOnce().then(function(data){
    // ...
    $scope.isDoneLoading = true;
});

Then you would just do this:

ng-if="isDoneLoading"

Or this, depending on your needs:

ng-show="isDoneLoading"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.