So I have played around with getting a promise to resolve in a service vs in a controller. I'd prefer to resolve it in the service so I can reuse the variable without having to resolve it multiple times.
The problem I'm having is that it works, but it's returning the data very very slowly. So I feel like I'm doing something wrong here. it takes about 5 or 6 seconds for my ng-options to populate. Which is better? And how can I improve my code so it runs faster?
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;
});
}]);
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>