如何将Phonegap相机与AngularJS集成

dre*_*ltz 9 javascript angularjs cordova

我正在试图找出将phonegap相机与AngularJS集成的最佳实践.我尝试的第一种方法是创建一个带有从ng-click调用的promises的工厂.另一种方法是将代码放在控制器内的ng-click内,但是它不可重复使用.也许可以从中做出指示?我相信还有其他一些方法."angularjs"的方式是什么?

这是我试过的工厂方法的一个例子....

HTML:

<button ng-click="takepic">Take Picture</button>
Run Code Online (Sandbox Code Playgroud)

控制器:

function picturePageCtrl($scope, Camera) {
    $scope.takepic = function() {
        // I'd like to push this into an array of "pics" here.
        // but it is hard to push() with promises.
        Camera.getPic();
    }
}
Run Code Online (Sandbox Code Playgroud)

工厂:

.factory('Camera', function($q) {
    var deferred = $q.defer();
    return {
        getPic: function() {
            navigator.camera.getPicture(
                function (imageURI) {
                    deferred.resolve(imageURI);
                },
                function (message) {
                    deferred.reject(message);
                },
                {
                    quality: 50, 
                    destinationType: Camera.DestinationType.FILE_URI
                }
            );
            return deferred.promise;
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

asg*_*oth 11

我个人会将逻辑放在一个指令中,因为它需要访问DOM函数(并且指令更适合于此).如果require: 'ngModel'在指令中使用,则可以使用它来存储输出值.

HTML:

<button camera ng-model='myPicture'>Take Picture</button>
Run Code Online (Sandbox Code Playgroud)

指示:

app.directive('camera', function() {
   return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, elm, attrs, ctrl) {
         elm.on('click', function() {
            navigator.camera.getPicture(function (imageURI) {
               scope.$apply(function() {
                  ctrl.$setViewValue(imageURI);
               });
            }, function (err) {
               ctrl.$setValidity('error', false);
            }, { quality: 50, destinationType: Camera.DestinationType.FILE_URI }
         });
      }
   };
});
Run Code Online (Sandbox Code Playgroud)

在您的控制器中,您可以$watch将模型推送到数组中:

$scope.myPictures = [];
$scope.$watch('myPicture', function(value) {
   if(value) {
      myPictures.push(value);
   }
}, true);
Run Code Online (Sandbox Code Playgroud)