How to retrieve and manipulate object properties in AngularJS after loading them from a service

In my AngularJS app, I have a local configuration file stored as a JSON file. I am using a service to fetch its content and then storing it in an object. The issue arises when trying to access the properties of this object outside of the callback function. Even though I can log the object inside the callback, it shows up as undefined when logged outside. Additionally, I attempted to use an angular expression as an attribute for a range slider element, but this resulted in an Angular parsing error. How can I access the config properties outside of the functions that call 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: My goal is to utilize the properties of the config object to set the minimum and maximum values of the slider.

function getConfigData() {
    return $http.get('/static/json/config.json')
        .then(getConfigDataSuccess);

    function getConfigDataSuccess(response) {
        var config = response.data;

        return config;
    }
}

Service

Answer №1

loadAgeSlider({});
fetchConfigData();

////////////////////////////////////////////////////////////

function fetchConfigData () {
  DataService.retrieve().then(loadAgeSlider);
}

function loadAgeSlider (configuration) {
  $scope.ageSlider = {
    minValue: configuration.options[0].min || 0,
    maxValue: configuration.options[0].max || 90,
    options: {
      floor: 0,
      ceil: 100,
      step: 1
    }
  };
}

Additionally, implementation of service:

function obtain () {
  return $http.get('/resources/data.json').then(success);

  function success (reply) {
    return reply.data;
  }
}

[Update] Multiple sliders:

modifySliders();
fetchConfigData();

////////////////////////////////////////////////////////////

function fetchConfigData () {
  DataService.retrieve().then(modifySliders);
}

function modifySliders (sliderConfigs) {
  sliderConfigs = sliderConfigs || {};
  var allSliders = ['ageSlider'];

  for (var key in myExpectedSliders) {
    var sliderName = allSliders[key];
    $scope[sliderName] = setSliderInfo(sliderConfigs[sliderName]);
  }
}

function setSliderInfo (sliderConfig) {
  sliderConfig = sliderConfig || {};
  return {
    minValue: sliderConfig.min || 0,
    maxValue: sliderConfig.max || 90,
    options: {
      floor: 0,
      ceil: 100,
      step: 1
    }
  };
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating a hierarchical structure of JSON data through iterative looping

Currently, I am in the process of creating a directive within Angular to assist with field validation. The functionality is working smoothly until it comes time to store the validation result. My objective is to store this information in an object structu ...

Tips for validating a URL in Cypress without having to actually visit the page

Is there a way to verify the URL without actually opening the page? The application is built on AngularJS and uses the ng-click method ($state.go) for navigation. I've researched Cypress stub and intercept options, but haven't found any solutions ...

What is the shebang used for in JavaScript?

In one article I came across, it was mentioned that by including #! /usr/bin/python in a file named testScript, running ./testScript from the command line would be the same as running /usr/bin/python testScript This concept seems plausible to me as most s ...

button does not change color upon clicking

I am currently working on a project where I am using Bootstrap to change the color of a button when clicked. However, it seems like there is an issue as the button is not changing its color upon clicking. Below is the code for my button - <td> ...

Altering value with Angular in a script element

Is there a way to dynamically change the radius of a circle based on user input without using angular curly braces in the script tag? I'm looking for an alternative method that mimics how Angular binds HTML properties. <script src="https://aj ...

Holding off $ajax requests until specific code finishes executing

I'm facing an issue with incorporating geolocation data into my $ajax call URL. Currently, both console.log(lat/lon) calls return the initial value of 0, indicating that the geolocation call is too late to provide the updated values. This results in t ...

Avoiding the <br> tag in list items with TinyMCE

I am currently using tinyMCE and I needed to enable the "force_br_newlines: true" option. Without this setting, if I press the "Enter" key twice and check the source code, I only see one <br> tag. However, when I set the option to TRUE, it creates a ...

"Seeking a more flexible JSON parser that allows for greater

I am in need of passing various strings that are formatted as json to a json parser. The issue is that jQuery.parseJSON() and JSON.parse() strictly support only a specific json format: If a malformed JSON string is passed, an exception may be thrown. For ...

What's the best way to ensure that only the most recent 100 entries are retained in a CSV file

Currently, I am working on an application that requires me to extract timestamp-based parameter values from various devices. The data is highly structured and because I have to retrieve 100k rows every few minutes, I haven't explored the option of usi ...

How can I extract the value from the element in JavaScript that has the same class as this

Currently, my app is designed to fetch data from a JSON file and display it dynamically. I have opted to use classes instead of pulling ID names from the JSON file to insert into HTML elements. However, I am encountering an issue - when using querySelector ...

The implementation of CORS headers does not appear to function properly across Chrome, Firefox, and mobile browsers

I encountered an issue while trying to consume a third party's response. The functionality works correctly in Internet Explorer, but fails in Chrome, Firefox, and on my mobile browser. Despite searching online and testing various codes, I continue to ...

Troubles with side menus causing issues with a tabbed interface on Ionic

I have a unique sliding menu application where each menu item opens up a view to populate data. Everything is functioning well, but in one specific view, I am trying to incorporate an Ionic pager with slides. It seems that the sliding menu is interfering w ...

Disabling hammer.js touch events with the onclick event

I have recently completed constructing a carousel slider with touch events for a website project. I am currently trying to find a way to deactivate the touch events (hammer) using click events. Below is the code snippet that I have been working on: The cl ...

Obtaining information through numerous JSONP requests

I am intrigued by the process of retrieving data using multiple jsonp requests. Is it practical? Currently, the code fragment below is what I am using in my CRA (pseudocode). import * as fetch from 'fetch-jsonp'; import * as BlueBird from ' ...

Issues with the JavaScript, HTML, and CSS Counter Implementation

Is there anyone who can assist me in making this code (available at https://jsfiddle.net/hmatrix/v3jncqac/) function properly? Purpose: My goal is to develop a counter that increments by specified values. My HTML: <body onload="incrementCount(10)"> ...

Does jQuery mobile lack a back button feature?

Thoughts swirling in my mind: <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title></title> <script src="<?php echo base_url();?>/assets/js/vendor/modern ...

Exploring JSON parsing using javascript?

I'm currently attempting to work through this webRTC example and have encountered an issue that appears to be minor in nature... The if statement consistently fails to return true, despite the fact that the console message indicates that the property ...

Using the inline calendar feature of Bootstrap 3 Datepicker to easily select and capture dates

I've been struggling to extract the selected date from my bootstrap 3 datepicker, and despite attempting to follow the documentation, I still can't grasp it. Here's what I tried: <div id="datetimepicker"> <i ...

Having difficulty with Angular's ng-options feature in a Select element

I'm currently tackling an issue with using ng-options to iterate through an array of objects and display specific properties in a select element. Upon querying the api/admin endpoint, I receive JSON data containing details of all users holding the ad ...

Navigate to a precise section of the webpage, positioned at a specific distance from the top

When scrolling on my page, the static header moves along with the user. However, when I link to a specific div using the standard method, the div appears behind the header. I would like to utilize: <a href="#css-tutorials">Cascading Style Sheet Tut ...