Ionic/Cordova: How to integrate Cordova Plugins into existing Ionic project?

后端 未结 7 2397
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-19 07:05

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 th

7条回答
  •  [愿得一人]
    2021-02-19 07:34

    You can install the plugin by run :

    $ cordova plugin add org.apache.cordova.camera
    

    Now that you have the plugin installed, you can use the camera API from your Javascript:

    function takePicture() {
      navigator.camera.getPicture(function(imageURI) {
    
        // imageURI is the URL of the image that we can use for
        // an  element or backgroundImage.
    
      }, function(err) {
    
        // Ruh-roh, something bad happened
    
      }, cameraOptions);
    }
    

    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:

    module.factory('Camera', ['$q', function($q) {
    
      return {
        getPicture: function(options) {
          var q = $q.defer();
    
          navigator.camera.getPicture(function(result) {
            // Do any magic you need
            q.resolve(result);
          }, function(err) {
            q.reject(err);
          }, options);
    
          return q.promise;
        }   } }]);
    

    This factory can be used in your controllers like this:

    .controller('MyCtrl', function($scope, Camera) {
    
      $scope.getPhoto = function() {
        Camera.getPicture().then(function(imageURI) {
          console.log(imageURI);
        }, function(err) {
          console.err(err);
        });
      };
    

    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):

    module.config(function($compileProvider){
      $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
    })
    

提交回复
热议问题