api调用后,ng-repeat列表不会立即更新

时间:2015-06-12 11:58:58

标签: javascript angularjs google-drive-api angularjs-ng-repeat

我的网络应用视图列出了嵌套列表中的文件夹及其子项:

<ul>
  <li class="folderLi" ng-repeat="folder in folders">
    <a href="" ng-click="listFolderFiles( folder )">{{folder.title}}</a>
    <ul >
      <li ng-repeat="child in folder.children">
          {{child.title}}
      </li>
    </ul>
  </li>
</ul>

当我加载初始文件夹列表时,列表会立即更新以显示文件夹。但是,此时每个文件夹上没有子对象。单击文件夹并且应用程序调用Google Drive API以检索文件夹的子项时,会填写该文件。控制器包括此功能:

$scope.listFolderFiles = function( folder ) {
  var request = gapi.client.request({
    'path': '/drive/v2/files',
    'method': 'GET',
    'params' : {
        'q' : "'" + folder.id + "' in parents"
      }
  });


request.then(function(response){
     //log successful response
     console.log(response);
     folder.children = response.result.items;
           }, function(response) {
     //log error
      console.log(response);
   })
  }

此功能可正确检索信息并更新模型。但是,子项的ng-repeat列表不会立即更新和显示。相反,它会在下次单击文件夹时更新并显示。似乎此函数在api调用完成之前更新视图,因此下次运行该函数时,视图会更新以显示最后一次API调用的响应。想法?

1 个答案:

答案 0 :(得分:0)

您正在尝试更新外部角度的知识。所以你的观点没有更新。您需要使用$scope.$apply()$timeout来运行摘要周期。

request.then(function(response){
     //log successful response
     console.log(response);
     //folder.children = response.result.items; //Required in case of $scope.$apply()
     $timeout(function(){folder.children = response.result.items;}); //Or $scope.$apply(); (Don't forget to inject $timeout in your controller)
           }, function(response) {
     //log error
      console.log(response);
   })
  }