因爲ionic框架是基於angularJS的,開發hybrid app混合應用的,但angularJS自己沒有太多對移動設備硬件的支持,因此找到兩種方法解決這個問題!javascript
一,ngCordova插件:ngCordova是在Cordova Api基礎上封裝的一系列開源的AngularJs服務和擴展,讓開發者能夠方便的在HybridApp開發中調用移動設備的功能,便可以在AngularJs代碼中訪問設備的Apihtml
二,html5plus:最近比較火的一個東西,也是爲了解決有關html5移動app去調用移動設備功能的問題,但最最要命的就是它和AngularJs是徹底分離的,兩家的,因此基於angularJS的項目用html5plus去調移動設備的功能會有不少問題!html5
一,主要參考文章 http://haomou.net/2015/01/07/2015_ionic_fileOP/java
http://ngcordova.com/docs/plugins/android
https://github.com/driftyco/ng-cordovagit
1,(在此以前配置好ionic環境,安裝好cordova,bower等)命令行進入到ionic項目下,安裝ngcordovagithub
命令行:bower install ngCordovaapache
2,安裝選擇圖片文件的插件數組
命令行:cordova plugin add https://github.com/wymsee/cordova-imagePicker.gitapp
3,安裝文件上傳的插件
命令行:cordova plugin add org.apache.cordova.file
cordova plugin add org.apache.cordova.file-transfer
4,(安裝完畢)修改index.xml文件(ng-cordova.js要放在cordova.js以前引入,它們兩個要放在ionic或angular的js文件以後引用)
<scriptsrc="lib/ngCordova/dist/ng-cordova.js"></script>
<scriptsrc="cordova.js"></script>
5,注入ngCordova依賴
angular.module('myApp',['ngCordova'])
6,在controller裏添加$cordovaImagePicker模塊,引入imagePicker方法(返回的圖片地址是file:///data/data/包名/cache/pic.jpg)
.controller('TodoCtrl', function($scope,$cordovaImagePicker) { $scope.images_list = []; // "添加附件"Event $scope.addAttachment = function() { nonePopover(); $ionicActionSheet.show({ buttons: [ { text: '相機' }, { text: '圖庫' } ], cancelText: '關閉', cancel: function() { return true; }, buttonClicked: function(index) { switch (index){ case 0:appendByCamera(); break; case 1: <span style="color:#ff0000;">pickImage();</span> break; default: break; } return true; } }); } //image picker var pickImage = function () { var options = { maximumImagesCount: 1, width: 800, height: 800, quality: 80 }; $cordovaImagePicker.getPictures(options) .then(function (results) { $scope.images_list.push(results[0]); }, function (error) { // error getting photos }); } })
7,頁面
<div class="list"> <div class="item" ng-repeat="img in images_list"> <img src="{{img}}" width="100%"> </div> </div>
總結:事實證實此方法效果比較完美,沒什麼問題,基於angularJS的項目選擇ngCordova插件就對了
二,要想在本身的項目中用html5plus有兩種方法(
1,Android離線打包(http://ask.dcloud.net.cn/article/38)(最後導出apk報錯,沒找到問題)
2,HBuilder新建html5plus項目,導入你工程的其餘文件(導入個人ionic項目用到的文件)
我用的第二種方法
)
1,獲取圖片的方法很簡單(p是圖片路徑爲本地圖片的真實地址)
function appendByGallery() { plus.gallery.pick(function(p) { $scope.images_list.push(p) }); }
總結:因爲angularJS有數據變化自動刷新的機制,因此當選擇圖片後回到主界面時,圖片數組數據增長了,應該刷新圖片界面但未刷新(不能顯示新加的圖片,必須點擊部分部位纔會刷新)(點擊例如一些按鈕,輸入框後圖片刷新出來,多是因爲用了html5plus後,破壞了angularJS的自動刷新的機制,點擊按鈕等又喚醒了它的機制,因而刷新)。
因此暫時基於angularJS的項目,用html5plus去調移動設備的功能會有問題!
感謝 http://haomou.net/2015/01/07/2015_ionic_fileOP/ 不少知識今後博主的文章中得到
(建議最好按照步驟安裝,此博主的demo我運行到手機老是報錯,未找到緣由,個人ionic項目能夠正常運行,因此ionic和cordova的環境應該沒什麼問題)
項目地址http://download.csdn.net/detail/superjunjin/8417273
原項目來自於http://rensanning.iteye.com/blog/2072034
此項目是基於cordova環境的(請提早安裝好cordova)
命令行找到項目目錄,運行項目到真機 cordova run android(或建立apk cordova run android)