The magic of Angular's data binding post-ajax retrieval

My situation is as follows: /items/item/123/edit
and I have a controller that combines both the view and edit functionalities:

...
if ($routeParams.id) {
          $scope.itemId = $routeParams.id;
          $scope.editMode = true;

          Item.getBoxes({id: $routeParams.id}).$promise.then(function (data) {
            $scope.data.boxId = [];

            angular.forEach(data, function (obj) {
              $scope.data.boxId.push(obj.id);
              $scope.boxCache[obj.id] = {id: obj.id, name: {id: obj.id, name: obj.name}};
            });

            $scope.items= data;
          });
        }
...

In most cases (7 out of 8), everything works fine but sometimes the data doesn't bind correctly to the view. I am unable to use $scope.$apply() or $scope.$digest() due to them being in progress.

Answer №1

It is recommended to use $scope.$apply only when no other tasks are currently in progress.

To determine if a $digest is already in progress, you can check the value of $scope.$$phase.

if(!$scope.$$phase) {
  //$apply or $digest
}

For a safer apply method, consider using:

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

Alternatively, you can utilize this service for handling asynchronous operations.

$timeout(function(),millisecond);

Another option is to use $evalAsync for executing expressions asynchronously: $evalAsync([expression], [locals]);

For more information, refer to: https://docs.angularjs.org/api/ng/type/$rootScope.Scope

Choosing between $evalAsync and $timeout depends on the specific situation:

  • If code queued with $evalAsync originates from a directive, it should run after Angular manipulates the DOM but before the browser renders it.
  • If code queued with $evalAsync comes from a controller, it should run before Angular manipulates the DOM (and before the browser renders), although this scenario is rare.
  • If code queued with $timeout runs after Angular manipulates the DOM and after the browser renders (which may result in flickering), especially in certain cases.

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

Error encountered: DOMException - Prevented a frame originating from "domain_name" from accessing a different origin frame

Utilizing the Mautic newsletter for my website has been a great experience. Here is the js code I've been using: /** This section should only be included once per page if manually copying **/ if (typeof MauticSDKLoaded == 'undefined') { ...

Obtain the attributes of the chosen option in a dropdown menu using AngularJS

When I first started working with Angular, I found the use of select dropdowns to be quite confusing. I have a JSON object that I am retrieving through an AJAX call and then populating my form with using AngularJS. In the dropdown menu, the setting.metric ...

Checking if a phone number begins with a zero using a regular expression

Is there a way to ensure that numbers entered into a field always start with a 0? Initially, I thought the company wanted to mandate entering 0 first, but I believe there might be a more elegant solution. function validateNumber(dataValues, setErrors) ...

Exploring the potentials of VivagraphJS alongside WebGL and the magic of event listeners

After coming across Vivagraph JS on GitHub, I was absolutely enthralled. However, I've encountered an issue that seems to be related to WebGL. My current objective is to: var graph = Viva.Graph.graph(); var layout = Viva.Graph.Layout.forceDirec ...

Creating a personalized pivot-table using the WebDataRock Javascript library with a unique configuration based on a

I'm having trouble getting this demo to work with the "hierarchy" parameter. Even when I specify the parameter value, it seems to apply the condition to the entire hierarchy chain. "conditions": [{ "formula": "#val ...

React - Received an unexpected string containing a template expression with no curly braces present in the string

Currently, I am enrolled in a React tutorial online. I have inputted the code exactly as it was shown on the screen. Strangely, it seems to be working perfectly fine in the video but not when I try it myself. Below is the code snippet: <Link to={&apos ...

I'm encountering inexplicable duplications of elements on my Wordpress site

Here is an example of my template header: <header> <?php if ( function_exists( 'jetpack_the_site_logo' ) ) jetpack_the_site_logo(); ?> <a class="menu-toggle">menu</div> <?php wp_nav_menu( array('them ...

Creating a tooltip for a specific cell within an AG grid react component is a useful customization feature

How can I customize the tooltip for a specific row in my AG Grid? I see that there is a tooltipField available in ColDefs, but I want to provide a custom string instead of using a field value. Is there a way to achieve this customization? ...

Reload iframe content using a .php file within a different iframe

I am currently working on a page that consists of 7 different iframes: <iframe id="leftframe" src="structure/leftbar.php"></iframe> <iframe id="headerframe" src="structure/header.php"></iframe> <iframe id="menuframe" src="struct ...

Display issue with React TypeScript select field

I am working with a useState hook that contains an array of strings representing currency symbols such as "USD", "EUR", etc. const [symbols, setSymbols] = useState<string[]>() My goal is to display these currency symbols in a select field. Currently ...

Retrieving values from all fields in a dynamic form using VuejsLet's say

In the process of developing an admin panel using Vuejs and tailwind CSS for managing exercises on a page, I have encountered some challenges. My current objective is to insert the dynamic form values into a Firebase real-time database. However, I am stru ...

What is the proper way to define the type for a functional React component by using object destructuring on props?

As I continue to learn TypeScript and work on declaring advanced types, I am faced with converting my CRA project to TypeScript. Within this project, I have a component that closely resembles examples from react-router-dom, but I have not come across any T ...

Loading input datalist in Firefox postponed

My goal is to implement an input field for a username that allows users to select from a wide range of names/usernames. I want them to be able to enter a partial string from the name or username. Instead of loading the entire list initially, I aim to load ...

What is the most effective way to retrieve IDs from Firestore and add them to the object arrays?

Currently working on a project that involves React and Firestore, I'm attempting to retrieve the Ids back into the objects array. Below is the code snippet: function grabIds() { setIsLoading(true); reference.onSnapshot((querySnapshot) => ...

The onPress function seems to be malfunctioning within the menu interface specifically on iOS devices

I am experiencing an issue where a problem only occurs on iOS devices, but Android works fine. My menu has a userMenu class. import Menu, {MenuItem, MenuDivider} from 'react-native-material-menu'; class UserMenu extends React.Component { ...

IsContainer and IsModel properties in Dragular are not functioning properly with the accept or canBeAccepted methods

Scenario 1 : Let's consider using two containers, named A (Drag Source) and B (Drop Source). Code snippet : dragularService(containerLeft, { containersModel: [DragularconTainer], copy: true, canBeAccepted: function(el, source) { ...

What is the best way to display my table?

In the index.php view, you will find my table located <table class="striped"> <thead> <tr> <th>Id</th> <th>Name</th> <th ...

Issue encountered in NestJS/TypeORM: Unable to modify the property metadata of #<Repository> as it only has a getter method

When attempting to launch my nestjstutorial app, I encountered the following error message. The backend is connected to a PostgreSQL database. TypeError: Cannot set property metadata of # which has only a getter at EntityManager.getCustomRepository (D:&b ...

Tips for choosing option values from the browser console in Angular

Is there a way to choose one of the list values directly from the browser console? I appreciate any assistance provided <select style="width: 100%" id="Select1" class="css-dropdowns ng-not-empty ng-dirty ng-valid ng-valid-required n ...

Experiencing issues when attempting to invoke Java code from Google App Engine?

My issue involves java classes being called from an html file using the following ajax code: $.ajax({ type: "POST", url:"http://www.verifiedalerts.appspot.com/verifiedalert?action=addIntrusionRules", dataType:"text", async ...