I have a service which loads some data and then stores it into local storage, for a Angular base mobile app. I'm calling this service in the run function of my main JS file, like this:
angular.module('myApp', ['ionic'])
.config(function ($stateProvider, $urlRouterProvider) {
})
.run(function (StartupService) {
StartupService.initialDataLoad();
})
This data loads in to local storage, and then in the init function of the first views controller I try to access this data in local storage and display it in a list:
angular.module('MemberInduction').controller('InductionListCtrl', function($scope, DataAccessService) {
$scope.init = function init() {
if (localStorage.getItem('MI.ApplicationData') != null) {
var data = DataAccessService.getInductionList();
$scope.inductionsList = data;
} else {
$scope.displayReloadMsg = true;
}
}
$scope.init();
});
As you can see in my init() function I access the data through a service, but when the controller initialises the data maybe loaded in localStorage, but at the time of initialisation the data isn't there. So my displayReloadMsg flag is set to true, causing a message to the user telling them to reload the app to display the loaded data.
How can I get the view to initialise once the data has loaded successfully? So that the view and controller only load from localStorage once the data has loaded?
Thanks
Stephen
you want to use resolve
on your main controller to make sure the data is loaded prior to accessing the controller.
See this example: https://thinkster.io/egghead/resolve-conventions
In the example below, the state transistion will not happen if the Flickr.search()
returns no data - full source for this example is here - http://codepen.io/aaronksaunders/pen/gboQVO
.state('flickr-display', {
url: '/flickr-display:query',
templateUrl: 'flickr-display.html',
controller: 'FlickrDisplayCtrl as flkr',
resolve : {
ImageData : function($stateParams, Flickr) {
return Flickr.search($stateParams.query);
}
}