AngularJS returns undefined on first ng-click

Create a system that fetches new events based on the date sent to the API using AngularJS. I am currently still participating in the AngularJS learning stages, so I am wondering if there is anything I am missing.

My problem is that the data is loading correctly on page load, when I click the button, when I get undefined

for $scope.newEvents

, even if it is successfully getting data from the API (I can see it in the console).

I tried to create a JSFiddle, but I am having problems working on it.

here is the html output ...

Output...

    <ul>
      <li ng-repeat="event in events | orderBy:'-event_date' ">
        <span >{{event.event_date}},{{event.event_name}}, {{event.event_venue}}, {{event.event_description}} </span>
      </li>
    </ul>

      

Request request in my js ...

var eventApp = angular.module('eventApp', ['ngRoute']);


eventApp.factory("services", ['$http', function($http) {

    var apiBase = 'http://example.net/angular-api/'

    var service = {};

    service.getEvents = function(latest_date){
        return $http.get(apiBase + 'events?latest_date=' + latest_date);
    }

    return service;   
}]);

      

When the page loads its work, it makes a successful request and updates $scope.events

...

var date = new Date();

$scope.todays_date = date.getUTCFullYear() + '-' +
    ('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
    ('00' + date.getUTCDate()).slice(-2) + ' ' + 
    ('00' + date.getUTCHours()).slice(-2) + ':' + 
    ('00' + date.getUTCMinutes()).slice(-2) + ':' + 
    ('00' + date.getUTCSeconds()).slice(-2);

$scope.events = [{}];

services.getEvents($scope.todays_date).then(function(data){
    $scope.events = data.data;

});

      

But when clicking the button that loads the function ng-click

, I get undefined for my data. At first I realized that there was something wrong with the date format, but the fact that it is successfully receiving data is what confuses me. Problems start from then

below ...

        $scope.addFiveNew = function (new_or_old) {

        if (new_or_old == 'new') {

            $scope.latest_date = $scope.getNewestDate();


            services.getEvents($scope.latest_date).then(function(data){
                $scope.newEvents = data.data;
            });

            console.log($scope.newEvents);

            // update the list (this is currently failing on first click)
            angular.forEach($scope.newEvents,function(item) {
                $scope.events.push(item);
            });


        }

      

this function in the controller creates the send date ...

$scope.getNewestDate = function() {
        var sortedArray = $filter('orderBy')($scope.events, 'event_date');
        var NewestDate = sortedArray[sortedArray.length - 1].event_date;
        return NewestDate;
    };  

      

Here's an example of some data ...

{
 "event_id":"1",
 "event_name":"Event 1",
 "event_date":"2014-09-26 00:00:00",
 "event_venue":"Limerick",
 "event_description":"stuff"
}

      

+3


source to share


2 answers


It seems to me that calling getEvents on your service returns a promise. Call. Then, on promise, it will asynchronously call the passed function. So your $ scope.newEvents = data.data; called after the rest of the statements in this block. I think you can change your .then expression to the following and it should work:



$scope.addFiveNew = function (new_or_old) {

    if (new_or_old == 'new') {

        $scope.latest_date = $scope.getNewestDate();

        services.getEvents($scope.latest_date).then(function(data){
            $scope.newEvents = data.data;
            console.log($scope.newEvents);
            // update the list (this is currently failing on first click)
            angular.forEach($scope.newEvents,function(item) {
                $scope.events.push(item);
            });
        });

    }
}

      

+2


source


The bit inside then

is asynchronous, so the rest of your code can run without updating the scope, returning your service method, right?



services.getEvents($scope.latest_date)
.then(function(data){            //whenever the service returns
  $scope.newEvents = data.data;  //update the scope

  console.log($scope.newEvents); //log the results

  // update the list
  angular.forEach($scope.newEvents,function(item) {
     $scope.events.push(item);
  });
});

      

+3


source







All Articles