在函数外部的 Angularjs 中访问 $http.get 的结果

Access the result of $http.get in Angularjs outside function

本文关键字:http get 结果 访问 函数 外部 Angularjs      更新时间:2023-09-26

尝试创建一个Date对象(仅使用时间)并在我的函数之外访问该值

任何帮助将不胜感激。请参阅下面的代码或我的 plunker

  var objts = "";
  $scope.today = function() {
        $http.get('time.json').success(function(data, status, headers, config) {
        objts   = new Date(data.time_start);
        objte   = new Date(data.time_end);
        console.log(data);
    }).error(function(data, status, headers, config) {
        console.log("No data found..");
  });  
    $scope.dt = objts;  // ---- Trying to use value of objts here ----
  };
  $scope.today(); 

谢谢

get 方法asynchronously执行。您当前正在get承诺解析功能之外设置$scope.dt值。

您应该在get承诺解析时设置 $scope.dt 变量:

$scope.dt = null;
$scope.today = function() {
  $http.get('time.json').success(function(data) {
    var objts = new Date(data.time_start);
    var objte = new Date(data.time_end);
    $scope.dt = objts;
    console.log(data);
  }).error(function(data) {
    console.log("No data found..");
  });
};
$scope.today();

编辑
您的问题实际上来自您创建日期的方式。你应该做这样的事情:

$scope.dt = Date.parse("2016-01-01 " + data.time_start);

请参阅日期文档,或时刻.js和分叉的 Plnkr