1

trying to create a Date object (using time only) and accessing that value outside of my function

Any help would be appreciated. See code below or my 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(); 

Thanks

1
  • you will only get async call response in their callbacks.. Commented Mar 7, 2016 at 16:36

1 Answer 1

2

The get method is executed asynchronously. You are currently setting the $scope.dt value outside the get promise resolution function.

You should set the $scope.dt variable when the get promise resolve:

$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();

Edit
Your problem actually comes from the way you create your date. You should do something like:

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

See the Dates documentation, or moment.js, and forked Plnkr

Sign up to request clarification or add additional context in comments.

2 Comments

Ok that makes sense, but I get the current time (not 08:00:00, the value in my json I want) when I do that. My plunker was updated to show what I mean
The problem lies in your date creation. You should do something like Date.parse("2016-01-01 "+data.time_start);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.