我正在使用以下解决方案,它允许 AngularJS 在与 Cordova 一起运行时以及在直接在浏览器中运行时被引导,这是我的大部分开发工作发生的地方。您必须从主 index.html 页面中删除 ng-app 指令,因为这是手动引导正在取代的内容。
更新:我已经切换到以下方法,我认为它更清洁。它适用于 Ionic 以及 vanilla Cordova/PhoneGap。它应该是 JavaScript 的最后一点运行 - 可能在 /body 标记之前的 script 标记内。
angular.element(document).ready(function () {
if (window.cordova) {
console.log("Running in Cordova, will bootstrap AngularJS once 'deviceready' event fires.");
document.addEventListener('deviceready', function () {
console.log("Deviceready event has fired, bootstrapping AngularJS.");
angular.bootstrap(document.body, ['app']);
}, false);
} else {
console.log("Running in browser, bootstrapping AngularJS now.");
angular.bootstrap(document.body, ['app']);
}
});
这是我使用的旧解决方案:
// This is a function that bootstraps AngularJS, which is called from later code
function bootstrapAngular() {
console.log("Bootstrapping AngularJS");
// This assumes your app is named "app" and is on the body tag: <body ng-app="app">
// Change the selector from "body" to whatever you need
var domElement = document.querySelector('body');
// Change the application name from "app" if needed
angular.bootstrap(domElement, ['app']);
}
// This is my preferred Cordova detection method, as it doesn't require updating.
if (document.URL.indexOf( 'http://' ) === -1
&& document.URL.indexOf( 'https://' ) === -1) {
console.log("URL: Running in Cordova/PhoneGap");
document.addEventListener("deviceready", bootstrapAngular, false);
} else {
console.log("URL: Running in browser");
bootstrapAngular();
}
如果您在使用 http/https 检测方法时遇到问题,可能是因为从 Web 将 Cordova 应用程序加载到手机中,您可以改用以下方法:
function bootstrapAngular() {
console.log("Bootstrapping AngularJS");
// This assumes your app is named "app" and is on the body tag: <body ng-app="app">
// Change the selector from "body" to whatever you need
var domElement = document.querySelector('body');
// Change the application name from "app" if needed
angular.bootstrap(domElement, ['app']);
}
// This method of user agent detection also works, though it means you might have to maintain this UA list
if (navigator.userAgent.match(/(iOS|iPhone|iPod|iPad|Android|BlackBerry)/)) {
console.log("UA: Running in Cordova/PhoneGap");
document.addEventListener("deviceready", bootstrapAngular, false);
} else {
console.log("UA: Running in browser");
bootstrapAngular();
}
请注意,您仍然需要与第一个示例相同的 bootstrapAngular 函数。
为什么要使用 Cordova/PhoneGap/Ionic 手动引导 AngularJS?
有些人一开始可能不知道您为什么要这样做。问题是您可能拥有依赖于 Cordova/PhoneGap/Ionic 插件的 AngularJS 代码,而这些插件要等到 AngularJS 启动后才能准备好,因为 Cordova 在设备上启动和运行所需的时间比普通的旧 Javascript 代码要长对于 AngularJS 来说。
所以在这些情况下,我们必须等到 Cordova/PhoneGap/Ionic 准备好后才能启动(引导)AngularJS,以便 Angular 拥有运行所需的一切。
例如,假设您正在使用 NG-Persist Angular 模块,它利用本地存储在浏览器上保存数据,iOS Keychain plugin(在 iOS 上运行)和 cordova-plugin-file(在 Android 上运行)。如果您的 Angular 应用程序尝试立即加载/保存某些内容,NG-Persist 对 window.device.platform(来自 device plugin)的检查将失败,因为移动代码尚未完成启动,您将得到只不过是一个白页,而不是你漂亮的应用程序。