【问题标题】:AngularJS access variable inside $http.get$http.get 中的 AngularJS 访问变量
【发布时间】:2015-06-26 09:09:06
【问题描述】:
app.controller('EntryCtrl', ['$scope', '$http', function($scope, $http){
    $http.get(something.json).success(function(data){
      $scope.entries = data;
    });
    abc = $scope.entries.timestamp;  <-- not working
}]);

经过搜索,发现$http是一个异步函数。所以我把它包装成一个函数,但还是不行。

app.controller('EntryCtrl', ['$scope', '$http', function($scope, $http){
    var getEntries = function(){ return
      $http.get(something.json).success(function(data){
        return data;
      });
    };

    $scope.entries = getEntries();
    console.log($scope.entries); // returns undefined
}]);

【问题讨论】:

    标签: angularjs angularjs-scope angularjs-controller angular-http angularjs-http


    【解决方案1】:

    你的console.log 在你的promise 毫无疑问地返回之前就被触发了。把console.log放到success里面。

    我可能会这样写:

    var getEntries = function(){ 
          $http.get(something.json).success(function(data){
            $scope.entries = data;
            console.log($scope.entries);
          });
        };
    
        getEntries();
    

    另外,如果似乎仍然存在问题,请使用 console.log(data) 看看你得到了什么。可能是后端问题。

    Here is a plunker 这说明了我的意思。您不需要像以前那样将其包装在函数中。 $http.get 已经是函数了。}

    【讨论】:

    • 我想在控制器内部的某处使用变量$scope.entries,而不仅仅是在成功内部
    • 你可以。这是 $scope。
    • 你为 $scope 做的任何东西都可以在控制器的任何地方使用,并且可以绑定到视图。
    • 怎么样?我试图在 $http.get 之外使用$scope.entries,但它返回 undefined
    • 问题是什么时候?将 {{entries}} 绑定到您的视图,然后使用我提供的代码进行 ajax 调用,并查看它是否更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 2015-01-31
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多