के साथ एक नियंत्रक में एक सेवा/फैक्ट्री बनाम एक वादे को हल करना, इसलिए मैंने एक नियंत्रक बनाम सेवा में हल करने का वादा करने के साथ चारों ओर खेला है। मैं इसे सेवा में हल करना पसंद करूंगा ताकि मैं इसे कई बार हल किए बिना चर का पुन: उपयोग कर सकूं।एंगुलरजेएस
मेरी समस्या यह है कि यह काम करता है, लेकिन यह डेटा को बहुत धीरे-धीरे वापस कर रहा है। तो मुझे लगता है कि मैं यहाँ कुछ गलत कर रहा हूँ। मेरे एनजी विकल्पों को पॉप्युलेट करने में लगभग 5 या 6 सेकंड लगते हैं। कौनसा अच्छा है? और मैं अपना कोड कैसे सुधार सकता हूं ताकि यह तेज़ी से चलता है?
सेवा में हल:
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;
});
}]);
नियंत्रक में समाधान किया गया:
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>
[वादा कैशिंग] (http://stackoverflow.com/a/18745499/1048572) मूल्य को कैशिंग करने से कहीं अधिक सरल है। – Bergi
@Bergi लिंक के लिए धन्यवाद। – allienx