Execute the controller function once all asynchronous calls to the Angular service have finished

I have integrated the Angular Bootstrap Calendar using a custom cell template and cell modifier. Within my controller, I need to retrieve configuration data from a service that is required by the cellModifier function before it is executed.

(function() {
  angular.module('formioAppBasic')
    .controller('calendarController', function($scope, moment, calendarConfig, $http, Formio, shiftService, AppConfig) {

    var vm = this;

    calendarConfig.templates.calendarMonthCell = 'views/calendar/dayTemplate.html';
    calendarConfig.dateFormatter = 'moment';

    vm.events = [];
    vm.calendarView = 'month';
    vm.viewDate = moment().startOf('month').toDate();
    vm.appConfig = AppConfig;
    vm.currentUser = Formio.getUser();
    // Retrieve station config.
    shiftService.getStationConfig().then(function(data) {
      vm.configSlots = data;
    });

    shiftService.getShiftsMonth(token, startDate, endDate)
      .then(onShifts, onError);

    var onShifts = function(data) {
      vm.events = data;
    };

    var onError = function(error) {
      vm.error = 'There was an error.';
    };

    var startDate = moment(this.viewDate).toISOString();
    var endDate = moment(this.viewDate).endOf('month').toISOString();

    var endpoint = APP_URL + '/shift/submission';
    var token = Formio.getToken();

    vm.cellModifier = function(cell) {
      // Code to generate data in the custom cell goes here.
    };

    $scope.$on('$destroy', function() {
      calendarConfig.templates.calendarMonthCell = 'mwl/calendarMonthCell.html';
    });
  });
})();

The necessary configuration data is fetched through calls to the shiftService service, which functions correctly. As per the documentation, the cell modifier function gets invoked from the mwl-calendar directive.

<h1>Shift Calendar</h1>

<h2 class="text-center">{{ calendarTitle }}</h2>

<ng-include src="'views/calendar/calendarControls.html'"></ng-include>

<mwl-calendar
  view="vm.calendarView"
  view-date="vm.viewDate"
  events="vm.events"
  view-title="calendarTitle"
  cell-is-open="true"
  cell-modifier="vm.cellModifier(calendarCell)"
>
</mwl-calendar>

In my current setup, the cellModifier is triggered prior to the completion of the requests made to shiftService.getStationConfig and shiftService.getShiftsMonth.

Given that the cellModifier is accessed externally from the controller, how can I organize my code to ensure that the cellModifier is only called after both shiftService calls have provided their respective data?

Thank you.

Answer №1

When cellModifier is called from an external source, the timing of its execution becomes uncertain. However, this lack of control can be managed effectively by delaying the execution of tasks until certain internal calls are completed.

let promise1 = shiftService.getStationConfig();
promise1.then(function(data) {
  vm.configSlots = data;
});

let promise2 = shiftService.getShiftsMonth(token, startDate, endDate);
promise2.then(onShifts, onError);

vm.cellModifier = function(cell) {
    $q.all([promise1, promise2]).then(function () {
        // perform actions here
    });
};

In addition to the above, make sure to include the injection of the $q service in your controller.

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

Ways to integrate AngularJS into your x-cart platform

Recently, I've been working on x-cart which utilizes the Smarty template engine. My client has requested to integrate angularjs into x-cart, but despite numerous attempts, I have not been successful in implementing it. After researching extensively on ...

User must wait for 10 seconds before closing a JavaScript alert

Can a JavaScript alert be set to stay open for a certain amount of time, preventing the user from closing it immediately? I would like to trigger an alert that remains on screen for a set number of seconds before the user can dismiss it. ...

What steps can be taken to ensure that a dropdown menu responds instantly to the JavaScript code provided?

Upon discovering this code snippet in a different answer (on jsfiddle), I noticed that it allows for the appearance of a text box when the user selects 'other' from the dropdown menu. However, when I include '<option value='0' s ...

Retrieve targeted HTML content using AJAX from a webpage that is already being fetched via AJAX

Looking to load a specific div on my webpage via Ajax call, but the content I want to load is itself loaded via ajax. This means I can't get the full HTML content as desired. function loadajax(){ $.ajax({ url: 'http://callcom-com-au.myshopify. ...

What is the best choice for code design patterns in a nodejs environment? What are the key considerations for creating a well-

Although I have a background in games development using C/C++/C#, I have recently delved into automated testing and now I am eager to learn more about backend development. My current project involves creating a platform for automated backups, building fr ...

What is the best way to activate matching dates within the rangeselector data?

A datepicker has been integrated into a highchart in the following manner. $(function() { $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function(data) { // Create the chart $('#co ...

Having trouble viewing the header in devtools for $http requests?

The data in the request header is not visible to me. Here's what I'm using: $http.post('http://localhost/api/validate', {}, { headers: key } ); https://i.sstatic.net/yioTT.png The form that gets passed during runtime is shown below: ...

Gather information to present in a specialized layout

i have two mysql tables order and orderitems. now i want to showcase this information using AngularJS on a separate screen. My table structure: Table order includes id, table_id, date_time Table orderitems has order_id, food_item, item_qty, deliver ...

Sorting an array based on shortest distance in Javascript - A step-by-step guide

I need to organize an array so that each element is in the closest proximity to its previous location. The array looks like this: locations=[{"loc1",lat,long},{"loc2",lat,long},{"loc3",lat,long},{"loc4",lat,long},{"loc5",lat,long}] Here's the funct ...

ExpressJS - The execution of JavaScript in this framework does not strictly follow a top-down approach

Having issues with this particular script not running as expected, particularly in the variable reassignment section. Below is the code snippet and output: // Code to Create New Open Market in the game let latestRowId = 1; var sqlQu ...

What is the best way to organize code into separate files while utilizing a module that needs to be included in every file?

In this particular scenario, I am utilizing a headless browser with Puppeteer Chrome and MongoDB. Take a look at the following code snippet: var browser = await puppeteer.launch() var page = await browser.newPage() var db = await MongoClient.connect(" ...

Calculate the total of the temporary information entered into the input field

I'm totally new to all of this and definitely not an expert, but there's something that really bothers me. I found a website where you have to complete a captcha to log in. It goes like this: <input type="text" class="form-contr ...

Is there a way to access the data attribute value from one component in another component without relying on an event bus mechanism?

In the 'App.vue' component, there is a data attribute called 'auth' that indicates whether the user is logged in. If it is empty, the user is not logged in; if it contains 'loggedin', then the user is authenticated. Now, let& ...

Include interactive buttons for every row within the ng-grid interface

I am using an ng-grid on my webpage to showcase details. I am wondering if there is a method to incorporate action buttons like edit or delete into the ng-grid. Is there a specific property in gridOpts that needs to be configured to enable these buttons? M ...

A step-by-step guide on integrating AngularJS login with Spring Security

My goal is to implement a login functionality using AngularJS to send the username and password to Spring Security, instead of relying on the traditional login.jsp method. Below is an outline of my configuration: -security_config.xml <http use-express ...

"Exploring the possibilities of Ajax in conjunction with Sol

I recently completed a tutorial on Ajax Solr and followed the instructions in step one. Below is the code I wrote: header.php: <script type="text/javascript" src="static/js/ajax-solr/core/Core.js"></script> <script type="text/javascript" s ...

Issues with Angular's ng-hide directive failing to function as expected

One challenge I am facing is getting ng-hide or ng-show in Angular to work properly based on a $scope variable. Currently, despite trying to hide the Hello, it remains visible. What mistake am I making? Controller: angular .module('myApp&apo ...

Manually sending the form via Ajax for submission

I'm facing an issue where I am trying to utilize ajax to call a servlet upon form submission. However, the ajax call is not being triggered and the page ends up reloading. To solve this problem, I have set up a manual trigger for the form submission, ...

Make sure that the iframe loads the next page with enough force to break out

My dilemma involves an iframe that loads the new tab page. When a user clicks on the thumbnail, it opens within the iframe. My goal is to have any subsequent load in the iframe redirected to window.top. Is there a way to achieve this without manually setti ...

Updating the content of a file on an iPhone

Is there a way to update the entire document content with a response from an ajax request? I've tested out using document.body.innerHTML and document.write(), which both work on desktop Safari. However, I'm looking for a solution that will also ...