Search code examples
angularjsgoogle-api-js-client

Googleapi - gapi not updating $scope object as expected in angularjs


I seem to get odd behavior from gapi.client.drive.files.list where I cannot update the scope from the promise it returns.

angular.module('myApp').controller("folder_controller", function($scope, $q, $http, $rootScope) {
    $scope.list_subfolders = function () {
        gapi.client.drive.files.list({
            'q': "mimeType = 'application/vnd.google-apps.folder'",
            'fields': "nextPageToken, files(id, name, parents, mimeType, description, starred, properties)"
        }).then(function(response) {
            $scope.subfolders = response.result.files;
            console.log($scope.subfolders); 
        }, function(error){
            console.log(error);
        });
    }
});

When I run list_subfolders()... the console.log displays $scope.subfolders fine... but the view never updates with that value - it is empty. I've tried various things including just assigning to $rootScope, but there is no way I can get the view to update with the $scope.subfolders.

Am I approaching this wrong? I can't understand why the variable is not updating.


Solution

  • Try this:

    angular.module('myApp').controller("folder_controller", function($scope, $q, $http, $rootScope) {
    $scope.list_subfolders = function () {
        gapi.client.drive.files.list({
            'q': "mimeType = 'application/vnd.google-apps.folder'",
            'fields': "nextPageToken, files(id, name, parents, mimeType, description, starred, properties)"
        }).then(function(response) {
            $scope.subfolders = response.result.files;
    
            // you need to refresh the view:
            $scope.$apply();
    
            console.log($scope.subfolders); 
        }, function(error){
            console.log(error);
        });
    }
    

    });