-2

Why I can't get my value through of one function? I'm doing rest requests for tests so you can get a date only and always tells me value undefined.

Example

$http.get('app/components/home/controller/test_calendar.json').then(function(value) {
    $scope.example2 = value.data.data[0];
    //console.log($scope.example2);
});

$scope.setDayContent = function(date, content) {
    console.log($scope.example2);
}; 

I get a value undefined with $scope.example2 or other value. With my first console the data appear well

Jose Cerejo
  • 231
  • 1
  • 5
  • 19

3 Answers3

3

I think you are calling setDayContent() before the http request (which is asynchronous) is done, so before $scope.example2 is set. You can check this by uncommenting the console.log in the 'then' function and see if you have your value.

If your function setDayContent() is called from a user action in the html (I suppose, because it is in the scope) - a button for example - you can disabled it until the data are loaded, something like this:

<button ng-click="setDateContent(...)" ng-disabled="!example2">
Thierry
  • 5,133
  • 3
  • 25
  • 30
0
  1. Because your $http.get() is asynchronous call.
  2. check the Web Console(F12), and XHR call responses, change your assignment and call setDayContent inside your callback function.
satya-j
  • 349
  • 1
  • 4
  • 11
0

you need to call the $scope.setDayContent function after getting value from json,note that $http call is asynchronous

// Code goes here

angular
  .module('myApp', [])
  .run(function($rootScope) {
    $rootScope.title = 'myTest Page';
  })
  .controller('testController', ['$scope', '$http',
    function($scope, $http) {

      /*my JSON file test_calendar.json
      test_calendar = {
        "data": [{
          "name": "nikhil"
        }]
      }*/

      $http.get('test_calendar.json').then(function(value) {

        $scope.example2 = value.data.data[0];
        $scope.setDayContent();
      });

      $scope.setDayContent = function(date, content) {
        alert($scope.example2);
      };


    }
  ])
<!DOCTYPE html>
<html data-ng-app="myApp">

<head>
  <link rel="stylesheet" href="style.css">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body data-ng-controller="testController">



  <p></p>
</body>

</html>
Nikhil Mohanan
  • 1,260
  • 1
  • 12
  • 23