Schw2iizer
Schw2iizer

Reputation: 845

ng-Repeat returning undefined within $scope.$watchCollection

When I console.log(result) on line 5, it returns just fine. The console.log($scope.notes) on line 11 returns undefined. Any ideas?

Here is my controller:

$scope.$watchCollection = (['parent_id', 'parent_type'], function(){
    $scope.loadNotes = function(){
        $http.get('/api/notes/' + $scope.parent_id + "/" + $scope.parent_type).success(function(result){
            console.log(result);
            $scope.notes = result;
            return result;
        });
    }
    $scope.notes = $scope.loadNotes();
    console.log($scope.notes);
});

Upvotes: 1

Views: 362

Answers (2)

Carson Drake
Carson Drake

Reputation: 171

Here is a way you can return a promise so the code will wait for the asynchronous call to complete before moving forward and defining $scope.notes.

$scope.$watchCollection = (['parent_id', 'parent_type'], function(){
    $scope.loadNotes = function(){
        return $http.get('/api/notes/' + $scope.parent_id + "/" + $scope.parent_type).success(function(result){
            console.log(result);
            //$scope.notes = result;
            return result;
        });
    }
    $scope.loadNotes().then(function(loadedNotes){
        $scope.notes = loadedNotes;
        console.log($scope.notes);
    });

});

Upvotes: 0

Ajay Narain Mathur
Ajay Narain Mathur

Reputation: 5466

Because $http.get is asynchronous so the line number 11 is executed before line number 5 so you get undefined there.

By asynchronous i mean the execution doesn't wait for $http to return the promise, it just keeps executing to next lines.

Upvotes: 2

Related Questions