我正在开发一个移动应用程序(Ionic,Angular,Phonegap),但Phonegap + AngularJS却有问题。
我的index.html
中有这个:
<body ng-app="myApplication" ng-controller="MainCtrl">
<ion-nav-view></ion-nav-view>
</body>
因此,我有一个名为
home.html
的模板,其中包含页眉,页脚和也由<ion-nav-view>
处理且随模板而异的内容。 home/something.html
中的此内容有一个单独的控制器,例如somethingCtrl
。问题:
我将
document.addEventListener
放在所有视图的主要MainCtrl
中。据我所知,只有在deviceReady被触发后才能使用Phonegap API。我的MainCtrl代码:
.controller('MainCtrl', function ($scope, $window, $rootScope, $location) {
document.addEventListener("deviceready", onDeviceReady, false);
alert('mainCtrl is loaded');
function onOnline(){
$rootScope.online = true;
}
function onOffline(){
$rootScope.online = false;
}
function onDeviceReady() {
alert('device is ready');
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
getLocalBooksStorageUrl();
}
function getLocalBooksStorageUrl(){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, null);
function fileSystemSuccess(fileSystem) {
var fp = fileSystem.root.toURL() + "/myApp"; // Returns Fulpath of local directory with my files
$rootScope.localStorage = fp;
}
}
})
我要在其中访问
$rootScope.localStorage
的控制器的代码(连接到该控制器的视图在我的应用中是第一个):.controller('MybooksCtrl', function ($scope, $rootScope) {
alert('myBooks is loaded');
console.log($rootScope.localStorage); // undefined
})
所以我有:
alert - mainCtrl is loaded
alert - myBooks is loaded
console.log - undefined ($rootScope.localStorage)
alert - device is ready
我该怎么办或实施以迫使第二个控制器的代码仅在设备准备就绪后才能运行?
最佳答案
您可以使用$apply
在角度上下文之外执行代码,然后触发摘要循环来更新视图。调用onDeviceReady()
函数后,将范围变量'deviceReady'设置为true。
.controller('MainCtrl', function ($scope, $window, $rootScope, $location) {
$scope.deviceReady = false;
document.addEventListener("deviceready", onDeviceReady, false);
alert('mainCtrl is loaded');
function onOnline(){
$rootScope.online = true;
}
function onOffline(){
$rootScope.online = false;
}
function onDeviceReady() {
$scope.$apply(function() {
alert('device is ready');
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
getLocalBooksStorageUrl();
$scope.deviceReady = true;
});
}
function getLocalBooksStorageUrl(){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, null);
function fileSystemSuccess(fileSystem) {
var fp = fileSystem.root.toURL() + "/myApp"; // Returns Fulpath of local directory with my files
$rootScope.localStorage = fp;
}
}
})
然后在您的“ MybooksCtrl”中,$ watch查看对deviceReady的更改:
.controller('MybooksCtrl', function ($scope, $rootScope) {
$scope.$watch('deviceReady', function(newVal) {
if (newVal) {
alert('myBooks is loaded');
console.log($rootScope.localStorage); // no longer undefined
}
});
})