After experimenting with resolving a promise in both a service and a controller, I have found that I prefer to resolve it in the service so that I can reuse the variable without having to resolve it multiple times. However, I am encountering an issue where the data is being returned very slowly, taking about 5 or 6 seconds for my ng-options to populate. This makes me wonder if I am approaching this incorrectly. Which method is better? And how can I optimize my code to improve its speed?
Promise Resolved In Service:
resortModule.factory('locaService',['$http', '$rootScope', function ($http, $rootScope){
locaService.getLocations=
function() {
return $http.get('/api/destinations').then(
function(result){
locaService.locations= result.data;
return locaService.locations;
}
);
return locaService.locations;
};
resortModule.controller('queryController',['$scope', 'locaService', function($scope, locaService) {
$scope.getLocations= locaService.getLocations().then(function(result){
$scope.locations= result;
});
}]);
Promise Resolved in Controller:
resortModule.factory('locaService',['$http', '$rootScope', function ($http, $rootScope){
locaService.getLocations=
function() {
locaService.locations= $http.get('/api/destinations');
//stores variable for later use
return locaService.locations;
};
}]);
resortModule.controller('queryController',['$scope', 'locaService',
function($scope, locaService) {
locaService.getLocations()
.then(
function(locations) // $http returned a successful result
{$scope.locations = locations;} //set locations to returned data
,function(err){console.log(err)});
}]);
HTML:
<select ng-click="selectCheck(); hideStyle={display:'none'}" name="destination" ng-style="validStyle" ng-change="getResorts(userLocation); redirect(userLocation)" class="g-input" id="location" ng-model="userLocation">
<option value=''>Select Location</option>
<option value='/destinations'>All</option>
<option value="{{loca.id}}" ng-repeat="loca in locations | orderBy: 'name'">{{loca.name}}</option>
</select>