angularjs - How to know when controller finished to load in angular? -
i have case app.run sends broadcast message controllers before of them loaded. , therefore don't catch event.
here example:
app.run(function($rootscope){ // event fast , 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 create flag in service seems workaround.
i thought create
$watchlistens on service flag , sends broadcast when controllers finished initialization.
is there more elegant way notify controllers when have loaded?
thanks,
as see have 2 options here. not suggest using $broadcast event system in instance due issue controllers may/ may not have been loaded.
1) can put promise on rootscope , attach statements in 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 device }) }); 2) if platform allow multiple ready functions registered add each controller should run if device ready.
app.controller('groupsctrl', function($rootscope, $scope){ ionic.platform.ready(function(){ //do device here. }); }); personally go #2 if possible keeps $rootscope cleaner, either way should fine. may try putting ionic.platform ready in service , registering that, if api ever changes controllers not have modified later down 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 device here. }); });
Comments
Post a Comment