Using The Native Device Calendar In Ionic Framework

A while back one of my subscribers asked me how to integrate the native device calendar into their Ionic Framework mobile application.  I didn’t know at first, but after some research I found a great Apache Cordova plugin by Eddy Verbruggen called PhoneGap Calendar Plugin.

Don’t let the plugin name fool you.  PhoneGap still works on Apache Cordova, just like Ionic Framework.

This guide will show you how to use the native device calendar with Ionic Framework using the AngularJS extension set, ngCordova.

Before we begin, if you plan to use Android it is important to note that you must have a calendar account on your device, otherwise the functions we use won’t work.  I tried to test on an Android emulator and it failed for exactly this reason.

With that noted, let’s go ahead and create a new Ionic Framework Android and iOS project:

It is important to note that if you’re not using a Mac, you cannot add and build for the iOS platform.

The next step is to install the Apache Cordova plugin by Eddy Verbruggen.  Using your Terminal or command prompt, run the following command:

At this point you can technically use the native calendar in your application, but we are going to make life easier by using ngCordova.  Download the latest ngCordova release and extract ng-cordova.min.js into your project’s www/js directory.

With the file included in your project you now need to include it in your www/index.html file:

It is very important that the above line be included before cordova.js, otherwise you will end up with strange and possibly breaking results in your project.

One final thing must be done in order to get ngCordova working.  We must include it into our angular.module directives list like the following in our www/js/app.js file:

Now we can start using the plugin.  Although the ngCordova documentation doesn’t explain this, the plugin’s official documentation proves that this plugin will work better for iOS since many of the commands are iOS only.

Open your www/js/app.js file and make it look like the following:

You’ll notice I ripped off the $cordovaCalendar.createEvent part from the ngCordova documentation.  That command should work for both Android and iOS and add events to the default calendar.

To use the createEvent() method above, open your www/index.html file and add the following code:

Because of the incompleteness of the plugin, unless you’re building strictly for either iOS or Android, I can’t recommend using the other commands unless you’re looking for a headache.  It isn’t all bad because in most scenarios you’ll only be setting calendar events in your application.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • Tiago Winehouse

    Very good..

  • Cris R

    Hey Nic!

    Thanks for your tutorial.

    I’m experimenting an issuea, and maybe you can help me. After add the plugin with cordova, I’m trying to build the project with these errors:

    clang: error: no such file or directory: ‘platforms/ios/tabApp/Plugins/nl.x-services.plugins.calendar/Calendar.m’

    clang: error: no input files

    And in fact the file is not there, however when I’m try copying the files to the path with issues, then another similar issues appear.

    cordova -v

    4.2.0

    ionic -v

    1.3.11

    Any idea?

    Thank you!

    • Do you have any spaces in your build path? That got me once before. And I’m not talking about in the path you provided, but instead say your home directory, or project directory.

      If that’s not it, try removing the plugin and adding it again. Occasionally Apache Cordova plugins will corrupt themselves.

      Sounds like you’re just having a config issue with Ionic rather than problems in your code.

      Let me know if either of that works.

      Regards,

      • Cris R

        Nic, thanks for your answer. I created a new blank project and now I dont see the error I mentioned before. However this is my new problem:

        Error: undefined is not an object (evaluating ‘n.plugins.calendar’)

        [email protected]://localhost:8100/js/ng-cordova.min.js:7:10891

        [email protected]://localhost:8100/js/app.js:25:37

        [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:20124:23

        http://localhost:8100/lib/ionic/js/ionic.bundle.js:50863:21

        [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:22178:28

        [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:22276:28

        http://localhost:8100/lib/ionic/js/ionic.bundle.js:50862:19

        [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:10823:25

        In the line 25 I’m calling to createEvent:

        ionicApp.controller(‘ExampleController’, function($scope, $cordovaCalendar) {

        My index.html:

        If you have any advice about it, I would be more than thankful!

        Cheers

        • I see http://localhost:8100/ in your logs.

          I encourage you to not use ionic serve or live reload. These features are for UI only. When you start introducing plugins they should not be used.

          I recommend you build an app binary and install it directly to your device or simulator exactly how you would natively.

          Let me know if that fixes it for you.

          Regards,

          • Cris R

            Nic,

            Thanks for your answer, nativaly is working perfectly 🙂

            Cheers!

          • gajula sreekanth

            hi am trying to build app on adroid platform when i click on create event

            it dosent open the native calender

            i installed app and tried on my mobile app

            this is my error log

            ystem.err( 3046): Exception: null
            W/PluginManager( 3046): THREAD WARNING: exec() call to Calendar.createEventWithOptions blocked the main thread for 172ms. Plugin should use CordovaInt
            erface.getThreadPool().
            W/CordovaPlugin( 3046): Attempted to send a second callback for ID: Calendar1729418646
            W/CordovaPlugin( 3046): Result was: “Invalid action”
            D/CordovaLog( 3046): file:///android_asset/www/js/app.js: Line 26 : There was an error: null
            E/Web Console( 3046): There was an error: null at file:///android_asset/www/js/app.js:26
            I/CalendarProvider2( 933): Sending notification intent: Intent { act=android.intent.action.PROVIDER_CHANGED dat=content://com.android.calendar }
            W/ContentResolver( 933): Failed to get type for: content://com.android.calendar (Unknown URL content://com.android.calendar)
            D/AlertReceiver( 828): onReceive: a=android.intent.action.PROVIDER_CHANGED Intent { act=android.intent.action.PROVIDER_CHANGED dat=content://com.andr
            oid.calendar flg=0x10 cmp=com.android.calendar/.alerts.AlertReceiver }
            D/AlertService( 828): 0 Action = android.intent.action.PROVIDER_CHANGED
            D/AlertService( 828): Beginning updateAlertNotification
            D/AlertService( 828): No fired or scheduled alerts

          • So your error says something is null on line 26 of app.js. You might want to start there.

            Regards,

          • gajula sreekanth

            i dint get u nic how can i fix this

            $scope.createEvent = function() {
            $cordovaCalendar.createEvent({
            title: ‘Space Race’,
            location: ‘The Moon’,
            notes: ‘Bring sandwiches’,
            startDate: new Date(2015, 0, 15, 18, 30, 0, 0, 0),
            endDate: new Date(2015, 1, 17, 12, 0, 0, 0, 0)
            }).then(function (result) {
            console.log(“Event created successfully”);
            }, function (err) {
            ====>> {this is line 26 in my app.js} console.error(“There was an error: ” + err);
            });
            }

          • Something is null. Can you put your full project on GitHub? I’ll check it out then.

            Regards,

          • gajula sreekanth
          • Sorry, but I’ll only look at projects on GitHub or Bitbucket

          • dimd13

            Have a same problem, plugin or example code from post not work on HTC One with 4.3 API 18 and work on Samsung Galaxy S5 with 4.4.4 API 19 (Genymotion virtual devices). Is author have any ideas

          • If it is only working on specific versions of Android, you should raise an issue ticket to the plugin developer so he can update the plugin:

            https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin/issues

            Regards,

  • singgihrs

    Hey Nic,

    Thank for your tutorial.

    Your tutorial is running successfully, but after I install it in android device, the button create event didn’t work.
    Please help me, thank you.

  • Yas

    Hi Nic, Thanks for the great tutorials.
    What can I do to solve the following problem?

    TypeError: Cannot read property ‘calendar’ of undefined
    at Object.createEvent (ng-cordova.min.js:7)
    at Scope.$scope.createEvent (controllers.js:67)

    • Can you confirm that you are NOT using live reload or ionic serve? These are known to have problems with native device plugins.

      If you’re not using those, can you confirm that you’re wrapping any calls to the calendar inside an $ionicPlatform.ready? Native device plugins don’t load instantly and must be queued up until they are ready. $ionicPlatform.ready does this for you.

      Regards,

  • singgihrs

    Hi Nic, Thanks for the great tutorials.

    I meet problem which must include calendar_id in method create event when I just update newest ionic and create new project 1 day ago.
    Before I upgrade ionic and create project with your tutorial it works successfully.
    So, where I must include calendar_id for new ionic project ?

    Please help me, thank you.

    • Hi,

      I really don’t know what you’re trying to explain. Can you please try again?

      Regards,

      • singgihrs

        Oh I was found why it need Calendar_id and make error, because the plugin when I get yesterday has changed but still not complete commit. And I download plugin again today, it works nice.
        Sorry for my question,
        Thank you
        Regards,

  • Monty Chawda

    Hello sir,

    Thanks for the tutorials.

  • Troy McKnight

    Nic – this may be a really silly question, but once you have the above code applied, what do you have to do to actually visually see a calendar in the app?

    • So the plugin does have API calls to access calendar events, but like I had mentioned in the article, cross compatibility support is a bit lacking at the moment. In any case, any event that you create in the app will be view able in the native calendar app.

      I encourage you to check out the official plugin documentation. I know the developer is constantly fixing stuff.

      Regards,

  • Zeeshan

    Hi,

    Having some issues with this, with this. I’ve run cordova plugin add, included ngCordova before cordova.js, and deployed it to my own nexus 4 without live reload using “ionic run android”. I used your code for the button, and nothing happens when I hit the button to add the event. So, I ran adb logcat, and it looks like one of the exceptions it’s throwing is “java.lang.ClassNotFoundException: nl.xservices.plugins.Calendar” Here’s some of the errors in adb log: http://i.imgur.com/7F6BE7f.png Any idea what’s wrong?

    • That’s not good!

      Java errors mean the plugin itself has problems. My guess is the developer introduced a bug. You probably want to open an issue ticket for the developer on his GitHub.

      Regards,

  • Valerio Radice

    It’s possible to have a sample download.zip ? i have error in starter module @ Failed to instantiate module ngCordova due to:

    • What is the error? Please paste the full logs.

      • Valerio Radice

        Uncaught Error: [$injector:modulerr] Failed to instantiate module starter due to:
        Error: [$injector:modulerr] Failed to instantiate module ngCordova due to:
        Error: [$injector:modulerr] Failed to instantiate module ngCordova.plugins due to:
        Error: [$injector:modulerr] Failed to instantiate module ngCordovaOauth due to:
        Error: [$injector:nomod] Module ‘ngCordovaOauth’ is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
        http://errors.angularjs.org/1.3.13/$injector/nomod?p0=ngCordovaOauth
        at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:8890:12
        at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:10594:17
        at ensure (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:10518:38)
        at module (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:10592:14)
        at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:12924:22
        at forEach (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:9150:20)
        at loadModules (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:12908:5)
        at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:12925:40
        at forEach (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:9150:20)
        at loadModules (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:12908:5)
        http://errors.angularjs.org/1.3.13/$injector/modulerr?p0=ngCordovaOauth&p1=…

        i try with older version of cordova .15 and work, but there is a problem, when i create calendar i see new id calendar but name is empty, i pass variable that contain( just verify with console.log) a string of calendar’s name.

        But this calendar will be sync with google calendar?

        • I would not recommend including both ngCordovaOauth and ngCordova. You’re going to get conflicts. I’ve done everyone a favor and included the ngCordovaOauth library in ngCordova so you only need to include ngCordova.

          If the error continues, it looks like you might have a typo somewhere.

          • Valerio Radice

            I only follow your tutorial, what Can i do ?

          • Sorry, my apologies. There was a bug in ngCordova. I submitted a fix and it should be merged soon.

            Regards,

          • Valerio Radice

            Thank you very much

  • Alex Sadri

    Is there a way to subscribe events, so they synchronize automatically? Actually, im using this plugin as a workaround. I have a backend which serves .ics files but i can’t get it to work in iOS because Mobile Safari doesnt seem to allow downloading of .ics files. (i get a url from backend and try to open it with window.open( url, “_system” ). Works fine on android, not on iOS. I tried to use the FileTransfer Plugin to directly download the ics file, doesnt work 🙁 So i ended up using this plugin but it just creates events. Any help, advice, ideas are really appreciated.

    • I don’t believe it is possible with this plugin. This plugin only offers very basic calendar functionality.

  • Fallesen

    Great idea but when trying to use this I run in to some issues. I’m working with the newest Ionic and Angular, where the notion of ng-controller callbacks aren’t really used. I seemed to have been able to add the button, but on the same page as where I use the Ionic Datepicker plugin, this however renders that function useless. I think it’s because I have added the same depencies into the same controller in controller.js, but having 2 different controllers linked to the same page, made the app not working at all.. Do you have any idea how to balance the two, so that I can use more than one plugin on that site/view? Or does it make sense what I’m trying to explain?

    • Fallesen

      Ha – never mind! Seems like a found my coding error! Sorry for the rant 🙂

  • Naveen Bellary

    Hi Nic,

    Thanks for the great tutorial.

    I want to know how to create calendar account in android emulator.

    Thanks,
    Naveen

    • I don’t think that is possible because I don’t think the simulator ships with Google Play Services.

      Regards,

      • Mohan Gopi

        Hi Nic, i am using Ubuntu and ionic ( 1.7.14 ). I have created ionic project and try to install the ngcordova plugin for calender but i am getting error and you have said to create an calender account for device, can you explain with some detail about creating that account and how to do it.

  • gas

    Help please,
    i followed this tutorial and i found it very good but when i’m running the code i’ve got this error: “Uncaught TypeError: Cannot read property ‘calendar’ of undefined ” which from to ng-cordova.js

    • Please include your full logs. No source code please.

      • Crazyman60

        Hi,

        I have the exact same problem, I assume it’s a version problem, but before anything, I prefer to ask, here are my logs:

        TypeError: Cannot read property ‘calendar’ of undefined

        Thanks!

        • Are you calling this plugin from with an $ionicPlatform.ready()? Can you confirm you’re not using Ionic Serve or Ionic View?

          • Crazyman60

            Actually, I’m dumb, you are completly right, should have thought a bit more, nights dev’ are not good lol.. I was using Ionic View, and necessarily, it’s not a native function for my OS so that error pulls up..

            Sorry for the dumb question and thanks for the reactivity, just fav’ed your website 🙂 your articles on Ionic are interesting to follow, thanks again.

          • The same stuff happens to me. Nothing to feel bad about. Sometimes just telling someone else about your code problems helps you to determine the fix.

            Always happy to help 🙂

          • Mohan Gopi

            Hi Nic, i am using Ubuntu and ionic ( 1.7.14 ). I have created ionic project and try to install the ngcordova plugin for calender but i am getting error and you have said to create an calender account for device, can you explain with some detail about creating that account and how to do it.

  • Shotbyabel A

    HI Nic! So this will work on Android devices.. They users with android devices must set up a calendar account? What kind of calendar account? Does Android have a special calendar that requires to subscribe?

    • They need to have a local calendar. I’m not sure if the plugin developer added support for Gmail calendars, ect.

  • muhsin k

    Hi Nic,

    When I go my calendar and click on that event I want to open my app. How to do that?

  • NR Arun

    Hi Nic,

    I am getting the below error. Any idea wht i am missing here? i am new to this framework.

    Error: n.plugins is undefined
    .[email protected]://localhost:8100/lib/ngCordova/dist/ng-cordova.min.js:7:17794
    [email protected]://localhost:8100/js/controllers.js:224:9
    [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js line 21977 > Function:2:221
    @http://localhost:8100/lib/ionic/js/ionic.bundle.js:57606:9
    $RootScopeProvider/this.$get<[email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:24678:16
    $RootScopeProvider/this.$get<[email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:24777:18
    @http://localhost:8100/lib/ionic/js/ionic.bundle.js:57605:7
    [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:12103:9
    [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:2870:3
    [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:2859:3
    [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:2932:5

    • Are you trying to use Ionic Serve, Ionic View, or Ionic Live-Reload?

      • NR Arun

        Thanks for the reply nic. I am using ionic serve.

        • Try it without ionic serve. I find that service to be particularly terrible when it comes to plugins.

          • NR Arun

            i tried with phonegap desktop app.The event is not getting added.

          • PhoneGap desktop app?

            I encourage you to stop trying to use services when testing your app. Please build the app, install it on a device or simulator and test it that way. If that doesn’t work still, view the logs the correct way and they should be more informative.

  • Rodrigo Robledo

    Hello Nic,

    I’m trying too but just to add to call js at index.html the console said “calendar is not defined”. I’m trying using “run” and see at my own Android device. Can u help us?

    Cheers,

    • I am not sure what you’re trying to tell me. Please try again.

  • nilesh thummar

    Hi Nic,
    Thanks for simple and useful tutorial.

    Query:
    $cordovaCalendar.createEvent gives result( i.e., interger 139 etc.,)
    It seems event id or reference.
    Can i use this result value for deleting event?
    If Yes, Please suggest snippet for it.
    Or
    I have to use $cordovaCalendar.deleteEvent process like below?
    http://ngcordova.com/docs/plugins/calendar/

  • salomon

    Hi Nic, I tried to use the Calendar-Plugin in my App but it doesn’t work so far. It would be great, if you check my file: https://drive.google.com/folderview?id=0ByyzcbG-1veETVNJdE9GRlJNbHc&usp=sharing

  • Saman Sattari

    Hi Nic,
    Thanks for the tutorial.
    Creating events in calendar the way that is described in this tutorial, will cause android google calendar to crash on the device.
    Maybe it is good if you highlight this part of the blog post as well (just for usability) :
    “Because of the incompleteness of the plugin, unless you’re building strictly for either iOS or Android, I can’t recommend using the other commands unless you’re looking for a headache. It isn’t all bad because in most scenarios you’ll only be setting calendar events in your application.”
    Because many different functions only work for one platform or the other one. Reference: https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin.
    I am not sure if it is a good idea to use this plugin (at its current state) for any app that is being used by end users.

  • salomon

    Hi Nic, pardon me for my last question. I didn’t know your rules at this time.

    Maybe you or somebody else here can help me with my question/problem. Creating calendars, adding events etc. works fine but how can I fetch the data from the calendar and show it in my app?

    For example, this is the line for listing all calendars:
    listCalendars(onSuccess, onError)
    When I call this function, the App opens a pop-up-window which shows the calendars with their attributes.

    I wanna display the calendars in a p-element instead of the pop-up and tried it with the following lines:
    var x = listCalendars(onSuccess, onError).toString();
    $( “#test” ).append(x);

    It doesn’t work and the app opens the same pop-up-window. Maybe you have some ideas?

  • Till

    Hi! How can I fetch the geo location of the calendar events?

  • Messaoud Mohamed

    Cannot read property ‘calendar’ of undefined

  • Gianfra

    Hi,
    is it possible to add in the system calendar and also get the system notification?
    I have see using createEventInteractively it opens the calendar and creates the event, I would like to not open the calendar but create the event and get the notification 🙂

    • Per the documentation, the createEvent function is silent.

  • Ignacio Norambuena G.

    How to convert datetime to format date to example??

  • Gopal Reddy

    hi guys, it is showing error….
    Error: undefined is not an object (evaluating ‘n.plugins.calendar’)
    please provide solution.

  • Luigi Casagrande

    Hi Nic. Thank you for your awesome tutorials. your blog helps me very much with my project.
    I would like to check if the event is already in my calendar. if its not it should create that event.
    I did this by searching for the event with:

    $cordovaCalendar.findEvent({
    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) {
    alert(“success”);
    }, function (err) {
    alert(“error”);
    });
    In the error part i created the event BUT even if the event is not there it always says success. How can i check if the event is in calendar or not? Thanks for your answers!