9

我正在尝试找出将 phonegap 相机与 AngularJS 集成的最佳实践。我尝试的第一种方法是创建一个带有从 ng-click 调用的 Promise 的工厂。另一种方法是将代码直接放在控制器内的 ng-click 中,但它是不可重用的。也许可以由此制定指令?我相信还有其他一些方法。“angularjs”方式是什么?

这是我尝试过的工厂方法的示例....

的HTML:

<button ng-click="takepic">Take Picture</button>

控制器:

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();
    }
}

工厂:

.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;
        }
    }
})
4

2 回答 2

11

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

html:

<button camera ng-model='myPicture'>Take Picture</button>

指示:

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 }
         });
      }
   };
});

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

$scope.myPictures = [];
$scope.$watch('myPicture', function(value) {
   if(value) {
      myPictures.push(value);
   }
}, true);
于 2013-01-27T21:23:00.473 回答
3

我添加了一些选项,并为像我一样遇到这篇文章的其他人更正了代码。谢谢你的帖子!

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.DATA_URL,
                sourceType : Camera.PictureSourceType.PHOTOLIBRARY,
                allowEdit : true,
                encodingType: Camera.EncodingType.JPEG,
                targetWidth: 1000,
                targetHeight: 1000,
                popoverOptions: CameraPopoverOptions,
                saveToPhotoAlbum: false 
            })
         });  
      }
   };
});
于 2014-06-23T22:12:55.170 回答