官网说明的cordovaCameraSource ,关于调用手机相机功能有简单介绍,但是如果ionic中有多个地方使用,就显得繁琐,所以我封装了一个拍照指令,供大家使用
1. 定义drCamera指令
directives.directive('drCamera',['$cordovaCamera','$ionicActionSheet',function($cordovaCamera,$ionicActionSheet){
return {
restrict:'AE',
replace:true,
scope:{drClick:'&',drSrc:'='},
template:'<img ng-src="{{drSrc}}" ng-click="getPhoto()"/>',
link:function(scope,element, attrs){
// 更新链接的属性
var lnk = element.find('img');
for (key in attrs.$attr){
lnk.attr(key,attrs.$attr[key]);
}
// 改变图片
scope.getPhoto = function(){
console.log('进入到改变图片的方法');
document.addEventListener("deviceready", function () {
console.log('进入到本地相机的调用方法');
// 图片配置
var optionsTakePhoto = {
quality: 100,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM,
targetWidth: 400,
targetHeight: 400
}
/**
* 拍照
* @type {{quality: number, destinationType: *, sourceType: *, allowEdit: boolean, encodingType: *, targetWidth: number, targetHeight: number, popoverOptions: *, saveToPhotoAlbum: boolean, correctOrientation: boolean}}
*/
var optionsMakePhoto= {
quality: 100,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 400,
targetHeight: 400,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: true,
correctOrientation:true
};
// 图片获取失败
var _onPhotoFail = function(message){
console.log('Photo Failed: ' + message);
}
// 图片获取成功
var _onPhotoDone = function(imageData){
console.log('图片获取成功');
scope.drClick({imageData:imageData});
}
// 获取图片
var _takePhoto = function(){
navigator.camera.getPicture(_onPhotoDone, _onPhotoFail,optionsMakePhoto);
}
// 生成图片
var _makePhoto = function(){
navigator.camera.getPicture(_onPhotoDone, _onPhotoFail, optionsTakePhoto);
}
$ionicActionSheet.show({
titleText :scope.titleText,
cancelText: '取消',
buttons : [{text:'拍照'},{text:'从相册中选取'}],
cancel : function(){},
buttonClicked : function(index){
switch(index){
case 1:_takePhoto();break;
case 0:
default:_makePhoto();break;
}
return true;
}
});
}, false);
}
}
}
}])
2. html中的指令使用
<dr-camera dr-src="headerPic" id="headerPic" alt="" class="circlepic"
style="width:80px;height:80px;"
dr-click="changePic(imageData)"
/>
3. controller的使用
$scope.changePic = function(imageData){
var imgageDatas=[];
imgageDatas.push(imageData);
SmsService.common08($scope.member.ucsId, imageData).then(function(resp){
if (resp.success){
var image = document.getElementById('headerPic');
image.src = "data:image/jpeg;base64," + imageData;
}
});
}
使用指令就不需要每个调用地方重复调用了,指令中得到imageData,将参数传递给调用的controller,剩下的业务逻辑就是controller的事情了