1

I'm an ionic/Angular n00b and I having trouble wrapping my head around how to do this.

I have a factory defined as such:

angular.module('starter.services', [])

.factory('Calendars', function () {

     var calendars;
     var success = function(message) {
        calendars = message;
        return calendars;
     };
     var error   = function(message) {alert("Error: " + message)};

     window.plugins.calendar.listCalendars(success,error);

     return {
         all: function() {
             return calendars;
         },
        get: function(calendarId) {
            return calendars[calendarId];
        }
     }


});

And I'm trying to retrieve the calendars within my controller like this:

.controller('CalendarsCtrl', function($scope,Calendars) {

    $scope.calendars = Calendars.all();

})

The factory method is being called but the results are not available until the 'success' callback is invoked so the CalendarsCtrl is always undefined.

How to solve this?

Edit - I've corrected the call within the controller. The same issue remains though, that the function does not return results until the success callback.

1
  • 1
    I notice you're not defining calendars outside of the success callback. But even after you do that, you should be retrieving the calendars in your controller with $scope = Calendars.all() Commented Oct 30, 2014 at 15:13

2 Answers 2

2

You will have to use a promise.

First add the dependency $q

.factory('Calendars', function ($q) {

then in all() you do this

all: function() {
    var deferred = $q.defer();

    window.plugins.calendar.listCalendars(function(data) {
        deferred.resolve(data);
    }
    ,function(error) {
        deferred.reject(error); // something went wrong here
    });
    return deferred.promise;

now this will make the return after the data has been resolved (no more undefined).

One last thing, now when you get the data back at your controller you do this

var promise = Calendars.all();
promise.then(function(data) {
  console.log('Success: you can use your calendar data now');
}, function(error) {
  console.log('Failed for some reason:' + error);
});

You can read some more about promises here: https://docs.angularjs.org/api/ng/service/$q

I know it's hard to grasp the first time.

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

Comments

0

Angular factories are returning an object, in order to call their methods you must call them with Calendar.all() which will invoke the inner function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.