Utilizing external functions within AngularJS Controller

I need to execute an external JS function that fetches data from a REST endpoint, which takes some time. The problem is that the graph is loading before the data is retrieved and inserted into it.

External JS:

function callEndpoint() {
    var sensorID = document.getElementById('sensorList').value;
    $.getJSON('http://193.61.148.125:443/SensorCentral/REST/SensorDataRangeNanos/19455746_3_10?startTs=0&endTs=9000000000000000000',
    function(data) {
        globalData = data;
     });
}

My root.js:

angular.module('root',['AngularChart'], function( $routeProvider, $locationProvider ){
    $routeProvider.when('/',{
        template: '<chart title="Bedroom Sensors" xData="lineChartXData" yData="lineChartYData" xName="Month" yName="Activations" subtitle="Sensor Usage"></chart>',
        controller:  MainCtrl
        })
})

Attempt at using a service:

angular.module('root',['AngularChart'], function( $routeProvider, $locationProvider ){
        service('myService', function() {
            this.callAlert = function() {
              callEndpoint();
        }});
    $routeProvider.when('/',{
        template: '<chart title="Bedroom Sensors" xData="lineChartXData" yData="lineChartYData" xName="Month" yName="Activations" subtitle="Sensor Usage"></chart>',
        controller: MainCtrl
        })
})

EDIT:

I'm making use of globalData in a function call (popGraph()) within MainCtrl:

function MainCtrl($scope, $http){
    callEndpoint();
    var data = {"xData": ["Mon", "Tues", "Wed", "Thurs", "Fri", "Sat","Sun"],"yData":[{
        "name": "Door",
        "data": [7.0, 6.9, 9.5, 14.5, popGraph(), 21.5, 25.2]
    }, {
        "name": "Drawer",
        "data": [2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8]
    }, {
        "name": "Cupbaord 1",
        "data": [9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6]
    }, {
        "name": "Cupboard 2",
        "data": [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0]
    }]}        
    $scope.lineChartYData=data.yData
    $scope.lineChartXData=data.xData
}

Answer №1

When creating a function within a main script in JavaScript without using closures, the function becomes attached to the window object. This means that you can simply call:

console.log(window.callEndpoint);

This will display your function in the console assuming your script is added to the page without closures altering scopes.

With Angular routing, you can utilize the resolve block easily like this:

$routeProvider.when('/',{
        template: '<chart title="Bedroom Sensors" xData="lineChartXData" yData="lineChartYData" xName="Month" yName="Activations" subtitle="Sensor Usage"></chart>',
        controller:  'MainCtrl',
        resolve: {
           myData: function() {
             return window.callEndpoint().then(function(data) { return data; });
           }
        }

        })

Inject myData into your MainCtrl controller and your data should be accessible upon initialization.

Update your function for fetching data as follows:

function callEndpoint() {
    var sensorID = document.getElementById('sensorList').value;

 return 
 $.getJSON('http://193.61.148.125:443/SensorCentral/REST/SensorDataRangeNanos/19455746_3_10?startTs=0&endTs=9000000000000000000').then(function(data) {
    function(data) {
        return data;
     });
  })
}

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

The ng-repeat directive fails to automatically refresh itself when a new item is added via a dialog box

As a beginner in AngularJs, I am currently working on CRUD Operations using $http and ASP.NET MVC. Here is what I have done so far: I utilize ng-repeat to display a list of "Terms". There is a button that triggers a dialog box for inserting new "Ter ...

Waiting to run a function until a specified function has finished its execution

I have a piece of code that needs to address synchronization issues related to the execution order of MathJax functions. Specifically, I need to ensure that all the MathJax operations are completed before running the setConsoleWidth() function. What is t ...

Is it possible to utilize onclick for various table cells in jQuery?

I have a situation where I need to loop through dates and display table content accordingly. Could someone please assist me in figuring out how to do this? index.html.erb <% @batches.each do |batch| %> <tr> **<td class = "pie" id ...

JavaScript that is subtle and lacks function parameters

Suppose you have: <div id="data" onclick="handleData(1)">Datum 1</div> and you prefer late binding instead: <div id="data">Datum 1</div> <script> $("#data").click(function() { handleData(1); }) </script&g ...

steps to initiate re-render of rating module

My first experience with React has been interesting. I decided to challenge myself by creating a 5-star rating component. All logs are showing up properly, but there seems to be an issue with the component not re-rendering when the state changes. Thank you ...

jQuery AJAX Concurrent Event

I have encountered a problem similar to ones discussed on SO, but none exactly match my specific issue. Here's the situation: var x = 5; if( some condition ){ $.ajax({ url:"...", success: function(response){ x = respo ...

Inject JSON data into a JavaScript array

I am dealing with a JSON file in the following format: [{"excursionDay":"2"},{"excursionDay":"3"},{"excursionDay":"4"}] My goal is to extract the values of excursionDay and store them in an array in JavaScript like this: dayValues = [2,3,4] Here is m ...

If the visitor navigated from a different page within the site, then take one course of action; otherwise

How can I achieve the following scenario: There are two pages on a website; Parent page and Inside page. If a user navigates directly to the Inside page by entering the URL or clicking a link from a page other than the Parent page, display "foo". However, ...

Enable the jQuery UI Autocomplete feature with Google Places API to require selection and automatically clear the original input field when navigating with the

I am currently using a jquery ui autocomplete feature to fetch data from Google Places... The issue I am experiencing is that when the user navigates through the suggestions using the up and down arrows, the original input also appears at the end. I would ...

What are the steps to manually activate input validation in Angular 2?

Having two inputs is the scenario here: The first input undergoes custom validator application The second input has a dynamic and editable value utilized in the custom validator If the custom validator is applied on the first input, then focus shifts to ...

Error when spaces are present in the formatted JSON result within the link parameter of the 'load' function in JQuery

I am facing an issue with JSON and jQuery. My goal is to send a formatted JSON result within the link using the .load() function. <?php $array = array( "test1" => "Some_text_without_space", "test2" => "Some text with space" ); $json = jso ...

Creating Dynamic Menus in Angular

My current setup is as follows: I am using a Dynamo DB table with 3 items, each representing a link in a menu. To fetch and display this data, I have set up a Lambda function which scans the table and sends a JSON response through an API gateway. Within ...

Converting JavaScript numbers into years and months format

Given an integer, for example 20, I am trying to calculate how many months and years are represented by that number. For 20, the result would be 1 year and 8 months. How can this be achieved using JavaScript? switch (props.term) { case (props.term ...

Launching an Angular JS application with a Java Spring backend on a standalone Tomcat server

Utilizing Intellij IDE, I developed a Java Spring and AngularJS application. After creating a war (Web Application:Exploded) file in Intellij, I placed it in the Tomcat webapps directory. Although the AngularJS code deployed successfully and was accessible ...

What is the Method for Multiplying Two ng-module Values in AngularJS?

In my application, I am utilizing the MEAN stack with AngularJS for the front-end. I have a table that contains two values - 'Payment value' with commas and 'commission' without commas. How can I multiply these two values? For example: ...

What changes can be made to this function in order for the arches to be positioned directly in front of the camera?

I devised a method that arranges arches in front of a camera, side by side: <!-- HTML --> <a-curvedimage v-for="(value, index) in model" :theta-length="42" :rotation="setThumbsRotation(value, index)"> </a-curvedimage> <a-camera ...

Exploring ways to check async calls within a React functional component

I have a functional component that utilizes the SpecialistsListService to call an API via Axios. I am struggling to test the async function getSpecialistsList and useEffect functions within this component. When using a class component, I would simply cal ...

Exploring the differences between Angular routes and Scala Play Framework routes

As I was working on creating a simple CRUD application using Scala Play framework and Angular, I came across two options: 1) I could utilize the Play framework route (located in the conf/routes file) 2) I could use Angular routes. Which option shou ...

Overabundance of Recursive Calls in Node.js Project Dependencies

After a tiring day at work, I noticed an alert for Windows SkyDrive showing that files couldn't be uploaded due to the path being too long. The lengthy directory structure made me chuckle at the technological limitation. However, it got me thinking: ...

Trigger event from a service without causing any interference to the $rootScope

I am currently developing an app using angularjs, with a central notification queue that any controller can push messages to and then digest them. Here is the service I have implemented: angular.module('app').factory('notificationSvc' ...