【问题标题】:Scope not updating after $http AJAX call [duplicate]$http AJAX 调用后范围未更新 [重复]
【发布时间】:2017-01-06 20:27:19
【问题描述】:

以下代码在我的控制器中 - 当我到达 console.log() 行时,什么都没有打印出来。 AJAX 调用返回一个有效的数组。我尝试使用 $scope.$apply 但我得到了一个进程已经在进行中的错误,我假设是因为使用 $http 会自动启动摘要周期:

var mmyApp = angular.module('myApp',['ui.bootstrap']).controller('TasksController',  TasksController);
 function TasksController($scope, $http) {
$scope.transactions = [];
$http.get('transactions').then(function (response) {
             $scope.transactions = response.data;     
     }, function (error) {
         throw error;
     });
console.log($scope.transactions);
}

【问题讨论】:

    标签: javascript angularjs ajax scope


    【解决方案1】:

    $http.get 是异步的。当您致电 console.log 时,您的 GET 请求尚未返回。您可以将其移动到手柄主体内以查看它是否有效:

    $http.get('transactions').then(function (response) {
                 $scope.transactions = response.data;     
                 console.log($scope.transactions);
         }, function (error) {
             throw error;
         });
    

    【讨论】:

      【解决方案2】:

      您应该知道在 AngularJS 中使用 $http 进行的 AJAX 调用是异步的,也就是说,它们不会与其余代码按顺序运行,除非您这样设置。

      因此当console.log被执行时,请求还没有完成处理。正确的做法是在AJAX调用中执行变量赋值后运行console.log,这样:

      var mmyApp = angular.module('myApp',['ui.bootstrap']).controller('TasksController',  TasksController);
      function TasksController($scope, $http) {
      
          $scope.transactions = [];
      
          $http.get('transactions').then(function (response) {
              $scope.transactions = response.data;
              console.log($scope.transactions);     
          }, function (error) {
              throw error;
       });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-15
        • 2015-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多