【问题标题】:Angular $scope variable is empty and not updated after setting it in HTTP GETAngular $scope 变量为空且在 HTTP GET 中设置后未更新
【发布时间】:2017-07-20 05:07:25
【问题描述】:

我将$scope.participants = [] 作为全局变量。我的问题是当我在调用下面的函数后在另一个函数中使用这个变量时。 $scope.participants 为空。但是,当我检查response.data 时并不是这样。

$scope.getParticipants = function(seminar_id,seminar_name,seminar_code) {
    $http({
        method: 'GET',
        dataType: 'JSON',
        params: { 'seminar_id' : seminar_id },
        url: 'getParticipants'
      }).then(function(response) {
          $scope.participants=response.data;
      });
  }

【问题讨论】:

  • 您是否在控制台中看到任何错误
  • $http 是异步调用。在$http返回数据之前$scope.participants为空。
  • 检查这是否可以解决您的问题。 stackoverflow.com/questions/18421830/…
  • @RogerNg 哦,现在我明白了!谢谢!!!!!!!!!!!!!!!!!!

标签: javascript angularjs angularjs-scope http-get


【解决方案1】:

你可以看看这个工作plnkr,你需要等到你的承诺解决。

$scope.getParticipants= function(seminar_id,seminar_name,seminar_code){
$http({
    method: 'GET', 
    dataType: 'JSON',
    params: { 'seminar_id' : seminar_id },
    url: 'getParticipants'
  }).then(function(response) {
      $scope.participants=response.data;
      $scope.callBack();
      console.log(response.data);
  });
}
$scope.getParticipants('a','b','c');

【讨论】:

  • 无法确定它会在 1 秒内完成
  • 我也试过了,1秒内完成不了。
  • 添加回调以在异步调用完成时通知范围内的某些函数调用。检查更新plnkr
猜你喜欢
  • 1970-01-01
  • 2019-05-11
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多