I have a case where app.run
sends a broadcast message to all controllers but before some of them actually loaded. And therefore they don't catch event.
Here is an example:
app.run(function($rootScope){
// I get this event too fast and GroupsCtrl still not ready
ionic.Platform.ready(function(){
// notify controllers on device ready
$rootScope.$broadcast('notifyCtrlOnDeviceReady', device);
});
});
and controller:
app.controller('GroupsCtrl', function($rootScope,$scope){
$scope.$on('notifyCtrlOnDeviceReady', function(event, device){
alert('notifyCtrlOnDeviceReady - done');
});
});
I thought to create some flag in the service but it seems like a workaround.
I also thought to create a $watch
that listens on a service flag and sends a broadcast when all controllers finished initialization.
Is there more elegant way to notify controllers when they have loaded?
Thanks,
As I see it you have two options here. I would not suggest using the $broadcast event system in this instance due to your issue where controllers may/ may not have been loaded.
1) You can put a promise on the rootscope and attach then statements in your controllers:
app.run(function($rootScope, $q){
var dfd = $q.defer();
$rootScope.deviceReady = dfd.promise;
ionic.Platform.ready(function(){
dfd.resolve( device );
});
});
app.controller('GroupsCtrl', function($rootScope, $scope){
$rootScope.deviceReady.then(function( device ){
//do something with device
})
});
2) If your platform allow multiple ready functions to be registered just add it to each controller which should be run immediately if the device is ready.
app.controller('GroupsCtrl', function($rootScope, $scope){
ionic.Platform.ready(function(){
//do something with device here.
});
});
Personally I would go with #2 if possible as it keeps the $rootScope cleaner, but either way should do fine. You may even try putting your ionic.Platform ready in a service and registering that, so if the API ever changes the controllers will not have to be modified later down the road.
app.factory("ionicPlatform"), function( $q ){
var ready = $q.defered();
ionic.Platform.ready(function( device ){
ready.resolve( device );
});
return {
ready: ready.promise
}
});
app.controller('GroupsCtrl', function($scope, ionicPlatform){
ionicPlatform.ready.then(function(device){
//do something with device here.
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With