如何使用onDeviceReady设置AngularJS应用程序并初始化Cordova的功能

How do I setup an AngularJS app with onDeviceReady and initialize functions for Cordova?

本文关键字:初始化 Cordova 功能 应用程序 何使用 onDeviceReady 设置 AngularJS      更新时间:2023-09-26

我正在开发我的第一个使用AngularJS的Cordova应用程序,我有点不知道如何为Cordova项目合并起始JS。

我现在有一个默认的index.js文件,它包含在Cordova中,我已经修改了它,以包含一些基于设备何时打开或脱机的事件。它创建一个对象(应用程序),并添加initialize、bindEvents和onDeviceready的函数。

我应该在哪里定义AngularJS应用程序?在文档底部的app.initialize()函数调用之后?或者,我可以完全放弃JS文件的原始Cordova结构,为onDeviceReady做其他事情吗?

谢谢!

基本上你可以在任何地方定义角度,我建议你使用一个单独的文件。你必须担心的是在cordova之前先加载angular。下面是一个如何使用服务克服这一问题的示例。

.service('cordovaReady', function($q){
 var cordovaDefer = $q.defer();
 //Note: if you want browser support you'll need to detect
 //what platform you're running because deviceready event won't be called
 //unless cordova is running.
 document.addEventListener("deviceready", cordovaDefer.resolve, false);
 return function(){
  return cordovaDefer.promise;
 };
});

每次你在应用程序中使用cordova插件时都会使用它,比如:

//$cordovaFacebook is just an example
.controller('someCtrl', function(cordovaReady, $cordovaFacebook){
 cordovaReady()
  .then(function(){
   //Plugins available here
   $cordovaFacebook.api('/me').then(...);
});