Search code examples
angularjscordovaionic-frameworkphonegap-plugins

Why am I not able to create a calendar event using $cordovaCalendar?


I would like to show an event reminder in the device calendar for my app and am trying to use ngCordova's $cordovaCalendar and the Phonegap Calendar Plugin to achieve this. Using the instructions on the ngCordova website I set up ngCordova and installed the plugin, but I am running into the following issue:

TypeError: Cannot read property <code>calendar</code> of undefined

The error points to the following code in the ng-cordova.js file:

 $window.plugins.calendar.createEvent(
          defaultOptions.title,
          defaultOptions.location,
          defaultOptions.notes,
          new Date(defaultOptions.startDate),
          new Date(defaultOptions.endDate),
          function (message) {
            d.resolve(message);
          }, function (error) {
            d.reject(error);
          }
        );

My controller code:

.controller('CalendarCtrl', function ($scope, $cordovaCalendar) {
  $cordovaCalendar.createEvent({
    title: 'Space Race',
    location: 'The Moon',
    notes: 'Bring sandwiches',
    startDate: new Date(2015, 0, 6, 18, 30, 0, 0, 0),
    endDate: new Date(2015, 1, 6, 12, 0, 0, 0, 0)
  }).then(function (result) {
    // success
  }, function (err) {
    // error
  });
})

Solution

  • These issues are usually caused by the plugin not being installed correctly or not waiting for all the Cordova plugins to be loaded, I think you may be dealing with the second issue here. Add $ionicPlatform as a dependency and try the following:

    $ionicPlatform.ready(function() {
      $cordovaCalendar.createEvent({
        title: 'Space Race',
        location: 'The Moon',
        notes: 'Bring sandwiches',
        startDate: new Date(2015, 0, 6, 18, 30, 0, 0, 0),
        endDate: new Date(2015, 1, 6, 12, 0, 0, 0, 0)
      }).then(function (result) {
        // success
      }, function (err) {
       // error
      });
    });
    

    The $ionicPlatform.ready ensures that all plugins are loaded before executing any of the defined functions inside of its scope, otherwise you try calling the plugin before it is loaded.