我有一个 Controller ,其中有 selectPicture
funtion
用于拍照并在 View 中使用此图片。
这是 Controller 中函数的代码:
$scope.selectPicture = function() {
document.addEventListener('deviceready', function() {
var options = {
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
correctOrientation: true,
targetWidth: 720,
};
$cordovaCamera.getPicture(options).then(function(imageURI) {
$scope.imageSrc = imageURI;
$scope.img = imageURI;
}, function(err) {
alert(err);
});
}, false); // device ready
}; // Select picture
Controller 代码变得困惑,因此我想将相机的逻辑投入使用,我执行了以下cameraService
:
.factory('cameraService', function($cordovaCamera, $ionicPlatform) {
var options = {
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
correctOrientation: true,
targetWidth: 720,
};
function takePicture () {
$ionicPlatform.ready(function() {
var img = $cordovaCamera.getPicture(options);
return img;
});
};
return {
takePicture: takePicture
};
});
此外,我在注入(inject)服务后将 Controller 中的代码修复为如下所示:
$scope.selectPicture = function() {
cameraService.takePicture().then(function(imageURI) {
$scope.imageSrc = imageURI;
$scope.img = imageURI;
}, function(err) {
alert(err);
});
};
但是,我似乎没有正确执行此操作,因为收到此错误:
Cannot read property 'then' of undefined at Scope.$scope.selectPicture
最佳答案
这是因为 takePicture
不返回 Promise(then
是一个 Promise 方法)。所以:
// service
function takePicture () {
return $cordovaCamera.getPicture(options);
};
// controller
$scope.selectPicture = function() {
cameraService.takePicture().then(function(imageURI) {
$scope.img = imageURI;
});
}
$ionicPlatform.ready(function() {
// initialization?
});
好吧,看来 getPicture
已经返回了一个 promise 。所以你只需要返回即可。由于 $scope.selectPicture
是用户在单击或点击时触发的,因此您无需每次需要拍照时都调用 $ionicPlatform.ready
。
关于javascript - Angular : pass data from service/factory to controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32027368/