I've got a basic ionic application which lists jobs on a page, when a job is clicked this calls my REST API and returns people on that job.
The problem I have is that when the job is clicked the page loads without the data initially then if I pull to refresh the page shows the results?
As the page is shown the results of the people should be there already not after I pull to refresh?
Does anyone know why my results don't show on page load?
My job list
Job 1 <a href="#/job/1">Begin</a>
Job 2 <a href="#/job/2">Begin</a>
Job 3 <a href="#/job/3">Begin</a>
When a job is clicked this loads my state & controller
State
.state('job', {
url: '/job/:jobID',
templateUrl: 'templates/job.html',
controller: 'jobCtrl'
})
Controller
.controller('jobCtrl', function($scope, $stateParams, $http, $state) {
$scope.jobId = $stateParams.jobID;
$scope.data = {};
$http.get('https://domain/api/job?token=' + localStorage.getItem("token") + '&job_id=' + $scope.jobId).then(function(successResponse){
$scope.return = successResponse;
$scope.data = $scope.return.data.data;
}, function(errorRepsonse){
$scope.error = errorRepsonse;
});
$scope.doRefresh = function() {
$http.get('https://domain/api/job?token=' + localStorage.getItem("token") + '&job_id=' + $scope.jobId).then(function(successResponse){
$scope.return = successResponse;
$scope.data = $scope.return.data.data;
$scope.$broadcast('scroll.refreshComplete');
}, function(errorRepsonse){
$scope.error = errorRepsonse;
});
};
})
The view which displays the people results.
<ion-refresher
pulling-text="Pull to refresh..."
on-refresh="doRefresh()">
</ion-refresher>
<ion-nav-back-button class="button-clear">
<i class="ion-arrow-left-c"></i> Back
</ion-nav-back-button>
<ion-list>
<ion-item class="item-remove-animate item-icon-right" ng-repeat="person in data" type="item-text-wrap">
<h2>{{person.name }}</h2>
</ion-item>
</ion-list>
You can use resolve
.state('job', {
url: '/job/:jobID',
templateUrl: 'templates/job.html',
controller: 'jobCtrl',
resolve: {
job: function($stateParams, $http){
return $http.get(...).then(function(resp){
...
// return job data
});
}
}
})
...
And then in your controller
.controller('jobCtrl', function($scope, job, $http, $state) {
$scope.job = job;
Your controller will only run after job
is resolved.
Also, you can display a loader while loading
Update
To make things clear: $http.get()
returns a promise. Once the promise is resolved then your controller function will be executed. Eventually, the $http.get
should return the data that you want to use inside your controller (in this case- the job info).
This way you don't need to start fetching information asynchronously inside your controller. Your controller starts with the data and should be kept simple.