Reputation: 63
I have a local configuration file I'm using for my AngularJS app. It's stored as local JSON file and am using a service to fetch its' content. Once I load the file the file, I'm storing it in an object. Now I have a range slider who's values are also stored in this config file. But I'm unable to access the objects' properties outside of the callback. Logging the object comes up as undefined if I log it outside the callback. Initially I had used an angular expression as an attribute in the slider element but that throws an Angular parsing error. How can I access the config properties outside of the functions that calls it from the service?
<div class="col-md-11">
<rzslider rz-slider-model="ageSlider.minValue"
rz-slider-high="ageSlider.maxValue"
rz-slider-options="ageSlider.options">
</rzslider>
</div>
HTML
function getConfigData() {
return Service.getConfigData().then(function(data){
$scope.config = data;
console.log("Config Data retrieved", $scope.config);
})
}
getConfigData();
$scope.ageSlider = {
minValue: 0,
maxValue: 90,
options: {
floor: 0,
ceil: 100,
step: 1
}
};
JS: I would like to use the config objects' properties to set the min and max of the slider.
function getConfigData() {
return $http.get('/static/json/config.json')
.then(getConfigDataSuccess);
function getConfigDataSuccess(response) {
var config = response.data;
return config;
}
}
Service
Upvotes: 1
Views: 883
Reputation: 1304
updateAgeSlider({});
getConfigData();
////////////////////////////////////////////////////////////
function getConfigData () {
ConfigService.get().then(updateAgeSlider);
}
function updateAgeSlider (config) {
$scope.ageSlider = {
minValue: config.options[0].min || 0,
maxValue: config.options[0].max || 90,
options: {
floor: 0,
ceil: 100,
step: 1
}
};
}
And service:
function get () {
return $http.get('/static/json/config.json').then(success);
function success (response) {
return response.data;
}
}
[Edit] Multiple sliders:
updateSliders();
getConfigData();
////////////////////////////////////////////////////////////
function getConfigData () {
ConfigService.get().then(updateSliders);
}
function updateSliders (configSliders) {
configSliders = configSliders || {};
var allSliders = ['ageSlider'];
for (var key in myExpectedSliders) {
var sliderName = allSliders[key];
$scope[sliderName] = getSliderConfig(configSliders[sliderName]);
}
}
function getSliderConfig (configSlider) {
configSlider = configSlider || {};
return {
minValue: configSlider.min || 0,
maxValue: configSlider.max || 90,
options: {
floor: 0,
ceil: 100,
step: 1
}
};
}
Upvotes: 1