The fusion of game loop and digest cycles by Angular services

I have successfully integrated my custom 2D JavaScript game engine with Angular. This game revolves around the space theme, where the engine takes care of simulating the space environment while Angular manages the trading menus with space stations and other activities.

The communication between the game engine and Angular is facilitated through Angular services acting as an intermediary. For example, when the game needs to log a message, it triggers

logServiceInstance.logDebug("Some message");
. There's a dedicated ConsoleController that displays these log messages in an HTML div using ng-repeat on $scope.logs, overlaying the game canvas:

angular.module('game')
   .controller('ConsoleController', ['$scope', 'LogService', function($scope, logService) {
    $scope.logs = logService.getLogs();
}]);

Since the game engine updates the service outside of Angular's knowledge, certain logs go unnoticed by Angular, leading all log methods (like logInfo, logError, logDebug, etc.) to engage with logService. Logs generated from the game pass 'true' as the second argument to initiate a digest:

addLog: function(log, updateContext) {
    console.log('(' + log.level + ') ' + log.message);
    logs.unshift(log);

    // NOTE: updateContext should be passed if log is
    // called outside of Angular context. This way Angular
    // reacts to the change.
    if(updateContext != null && updateContext === true) {
        // notify angular of a change
        $rootScope.$digest();
    }
}

However, there seems to be consistency issues with the ConsoleController in fetching log messages. Some logs do not appear on the HTML display but are visible in the JavaScript console. Moreover, I am encountering errors related to triggering multiple digests.

Queries:

  • How can I determine if a digest is already underway from another source?
  • While services seem to offer a convenient approach for sharing states between two frameworks, is this pattern considered unfavorable? If so, why?

Any insights from experienced Angular developers would be greatly appreciated.

Note: Find the game engine at

Answer №1

Question 1:

Is it possible to determine if a digest is currently being processed by another source?

if (!$rootScope.$$phase) {
    $rootScope.$digest();
}

Alternatively, you can use

$rootScope.$$phase || $rootScope.$digest();

Depending on your specific scenario, you may need to use

$rootScope.$$phase || $scope.$digest();
please note the use of $scope instead of $rootScope

Question 2:

Using services to pass states between two frameworks seems like a good approach, but is this considered a bad practice? If so, why?

It is actually recommended to use this pattern. Services act as Singletons, making them ideal for storing shared data.

Check out: Sharing data between AngularJS controllers

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

Navigate to the date selector and select the following month

<button class="mat-calendar-next-button mat-icon-button" mat-icon-button="" type="button" ng-reflect-disabled="false" aria-label="Next month"><span class="mat-button-wrapper"></span><div class="mat-button-ripple mat-ripple mat-button-r ...

The step-by-step guide to automate clicking on an angular dropdown menu using Selenium

Having some trouble using python selenium to automate report generation on a website. The javascript is making it difficult for me to identify the element I need to click on the page. When inspecting the element in Firefox, there is a DOM Event icon that c ...

The application of the template string expression is not carried out by $compile in the link function of a directive

I'm still learning AngularJs and running into a few issues with the code below. return { require: ['^myElement'], restrict: 'EA', replace: true, scope: true, link: function (scope, element, ...

Error: The JavaScript function you are trying to use is not defined

Hi there, I'm new to javascript and angularjs. I've created a function in my controller to open a website when clicking on a button. However, I'm encountering an error message saying ReferenceError: openWebsite is not defined when trying to ...

The error message "Function 'titleCtrl' is not defined, received undefined" was raised

Hi there, I'm a beginner in AngularJS and I've been encountering the error mentioned above in my Firebug console. Here is my code: index.html: <html ng-app manifest="/manifest.appcache"> <head> <meta charset="utf-8> < ...

Fire the $scope.submit() function of blueimp in Angular using programmatic methods

Using the submit() event of blueimp file uploader within the DOM works perfectly fine, like this: <span class="btn" ng-click="submit()">Go</span> But when trying to call $scope.submit(), it doesn't seem to function correctly: <span c ...

Utilize Angular service to deliver on a promise

Currently, I have a service that is responsible for updating a value on the database. My goal is to update the view scope based on the result of this operation (whether it was successful or not). However, due to the asynchronous nature of the HTTP request ...

What is the best way to organize JSON files data in a specific sequence?

I successfully converted 3 JSON files into an HTML page using AngularJS. Here is the code I used: Factory code app.factory('myapp', ['$http', function($http) { function getLists() { var tab = ['url1', 'url2 ...

Issues with locating Angular JS Text Area using Selenium Locator

Can you recommend a method for identifying the text area in a web application? <div contenteditable="true" id="taTextElement9662867992554610" ta-bind="ta-bind" ng-model="html" placeholder="Enter Role Requirements" class="ng-isolate-scope ng-pristine n ...

Issues arise in mobile Safari when attempting to load JavaScript files, resulting in

Encountering an issue with my Angular app on mobile Safari during the initial load, where it hangs on a blank page for nearly 2 minutes. Interestingly, the app functions perfectly on other browsers, including Mac Safari and iPad Safari. Initially, I suspe ...

Using ng-click to manipulate variables within a list

In my ionic/angular/phonegap app, I have a list of items and I'm attempting to use an action sheet to pass in the variables. However, I am having trouble accessing the variable on the same line as the ng-repeater. Here is the markup: <ion-view vi ...

Struggling to implement translation in Angular with Angular Translate

$scope.barChartData.labels.push(moment(currentDate).format("YYYY-MM-DD") + " $filter('translate')('To')" + moment(currentDate).add(4, 'days').format("YYYY-MM-DD")); Currently attempting to translate the word "To" ...

Issue with Cross-Origin Resource Sharing when using the browser's back button

I am facing an issue with CORS in my ASP.NET Web API 2 Service. I have multiple client (angular) applications communicating with the service, each published on different subdomains. For example: service.mydomain.com app1.mydomain.com app2.mydomain.com ...

Troubles arise when using $resource without initializing it with the new operator

Trying to utilize the Angular promise API in my application has left me feeling a bit puzzled. I set up a factory as shown in the code snippet below: factory('transport', function ($resource) { var baseUrl = "http://aw353/WebServer/odata/Pay ...

Angular encountered an issue with an HTTP POST request, as the 'Access-Control-Allow-Origin' header was not found on the requested resource

I have been attempting to transmit data to a servlet using Angular HTTP POST requests. var httpPostData = function (postparameters, postData){ var headers = { 'Access-Control-Allow-Origin' : '*', &a ...

Web API Implementation of Null-Safe Empty List Handling

I have a scenario where an angular controller is making a POST request to a web API method. I attempted to implement null safety with the IEnumerable, but it ended up causing the IEnumerable to always be empty. Here is the angular call: $http.post(custom ...

AngularJS: Implementing a toggle click function for a list of items within an iframe

Here's the workflow I'm dealing with: I have a collection of items, each having an ng-click event that triggers the display of an iframe below the clicked item. The process works like this: When clicking an item, a hidden div tag beneath it ap ...

Having challenges retrieving information from MySQL in AngularJS

As a beginner in angularJS, I am trying to display all customers from MySQL. Here is the code I have written in the controller and service: app.controller('CustomersController', function ($scope, customersService, $http) { init(); function ini ...

Experiencing problem with route and post request in my angular.js/express/node.js application

Below is the code for my Angular controller with a post request: $http.post('/formDevis', $scope.formData).then(function(response) { if (response.data) { $('#successModal').modal(); console.log(response); } }, function(resp ...

Two ng-click events are triggered within a nested ng-click

I am facing an issue with using the ng-click within a nested list under another list that also has a ng-click event. Here is my code snippet: <ul> <li ng-repeat="facet in node.Facets" ng-click="updateNav(facet.Action)" ng-cloak & ...