ng-Repeat returning undefined within $scope.$watchCollection

363 views Asked by At

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);
});
2

There are 2 answers

0
Ajay Narain Mathur On BEST ANSWER

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.

0
Carson Drake On

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);
    });

});