ionic ngCordova插件安装

时间:2023-03-08 16:37:01

ngCordova的安装配置

官网提供了两种安装的方法: 
1. 使用bower来安装 
2. 下载zip文件

推荐使用bower安装,在使用bower之前,我们电脑中需要先配置bower。bower的配置非常简单:

bower简介:

Bower是一个客户端技术的软件包管理器,它可用于搜索、安装和卸载如JavaScript、HTML、CSS之类的网络资源。

准备工作:

  • 安装node环境:node.js
  • 安装Git,bower从远程git仓库获取代码包:g

安装bower:

使用npm,打开终端,输入:

npm install -g bower

其中-g命令表示全局安装

这时候我们就可以使用bower来安装我们的ngCordova。

安装ngCordova

进入到工程目录,使用bower工具安装:

bower install ngCordova

bower ECMDERR Failed to execute git ls-remote --tags,
如果git报错的话,需要配置下GIT如下:
git config --global url."https://".insteadOf git://
 

稍作等待,我们的ngCordova就安装好了。

我们查看一下我们的项目,发现ngCordova已经在“项目路径\www\lib”下面:

ionic ngCordova插件安装

接着,将ng-cordova.js 或者 ng-cordova.min.js文件include到我们的index.html。

<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>

注意:ng-cordova.js文件必须在cordova.js之前并且在 AngularJS / Ionic文件之后(因为ngCordova depends on AngularJS)

在angular中添加ngCordova依赖

angular.module('myApp', ['ngCordova'])

通过deviceready event包装每个插件的调用

(不知道有没有翻译错。。)

在使用每个插件之前,必须先检测设备是否就绪,通过cordova内置的原生事件deviceready来检测,如下:

document.addEventListener("deviceready", function () {
$cordovaPlugin.someFunction().then(success, error);
}, false); // OR with IONIC $ionicPlatform.ready(function() {
$cordovaPlugin.someFunction().then(success, error);
});

ngCordova相机插件的使用

现在我们根据官网的文档来自己写一个小demo。

为了于cordova插件进行对比,我们还是使用上一讲的项目(即创建ionic项目时默认的那个)。

首先我们还是要安装插件的:

cordova plugin add cordova-plugin-camera

templates/tab-dash.html中的代码跟上一讲一样:

<ion-view view-title="Dashboard">
<ion-content class="padding">
<h2> Camera Test </h2>
<img id="imageFile" src="./img/ionic.png" width="100px" height="100px"/> <button ng-click="openCamera()">openCamera</button> </ion-content>
</ion-view>

在controllers.js中修改“DashCtrl”这个controller:

angular.module('starter.controllers', [])

.controller('DashCtrl', function($scope, $cordovaCamera) {

  document.addEventListener("deviceready", function () {

    var options = {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false,
correctOrientation:true
}; $scope.openCamera= function(){
$cordovaCamera.getPicture(options).then(function(imageData) {
var image = document.getElementById('imageFile');
image.src = "data:image/jpeg;base64," + imageData;
}, function(err) {
// error
}); }, false;
})
})

注意,在app.js记得注入’ngCordova’:

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services','ngCordova'])

实际演示效果跟上一讲中使用cordova插件没有太大的区别,就不贴图了。

在上面的代码中,我们关于插件的使用都是在

document.addEventListener("deviceready", function () {})

中进行的,这也即我们在上面讲的通过deviceready event包装每个插件的调用

通过对比可以发现,我们的controller中的代码比上一讲中直接使用cordova简单了许多而且更符合我们AngularJs的代码的编写。

所以我还是建议使用ngCordova进行插件的使用,当然是那些已经封装好的。自定义插件是另外一回事。