I have an Ionic project where I need the Cordova Camera plugin (which I now installed successfully). But in my project the Camera API is still not available, i.e. I get error thrown:
ReferenceError: Camera is not defined
at Scope.$scope.takePic
How do I active the plugin API(s) to be used in an Ionic project? Documentation about this seems to be rather nonexistant or very well hidden.
Follow these steps:
1. Include ngCordova before
cordova.js
You can found the same description in the docs.
2. Add your plugin on the command line
You can find this step in the docs in the section of your specific plugin.
3. Remember that cordova is not available while working in the browser
So when using the
$cordovaCamera.getPicture
the library is calling internallynavigator.camera.getPicture
which is not available when developing in the desktop browser. Further readingThe ngCordova / Ionic team is currently working on mocks you can use to avoid problems like that.
You can download ngCordova here: http://ngcordova.com/docs/install/
Update: There is Ionic Native now, it's like ngCordova but for ES6 and TypeScript.
You need to inject
Camera
into the controller, like so:Note that there is not a dollar sign before
Camera
. This really should be documented more explicitly.Also, you will need to add a factory to your services.js:
I'm trying to figure out how to use standard Cordova plugins with Ionic myself, but the ionic team just recently built ngCordova--an angular wrapper for common cordova APIs, which includes the Camera api you want to use. Would suggest using that: see their docs for more info.
Open a terminal in your app's root directory and add the plugin via
Edit:
the new command is:
You can install the plugin by run :
Now that you have the plugin installed, you can use the camera API from your Javascript:
This will prompt the user to take a photo, and will return the local URL of the image that you can then use inside of an tag or use for a CSS background image.
You can use the code below for a simple wrapper over the Camera plugin that makes it easy to asynchronously grab photos:
This factory can be used in your controllers like this:
Which will open the Camera when getPhoto() is called (from a button click, for example).
Depending on how you request the data back from the Camera and use it in your Angular markup, you may have to whitelist image URLs so Angular allows file:// URLs (for example, if you are using ng-src for an tag):
Go to the project directory.
Run this command:
(Hope this helps others.)