The user interface does not get refreshed right away; it only shows the changes after the

Here is an example of HTML:

<div ng-repeat="user in controller.users">
    <p>{{user.name}}</p>
    <button ng-click="controller.deleteUser(user)" value="delete"></button>
</div>

Next, we have the controller code:

vm = this;
vm.users;

activate();

function activate() {
    service.getUserList().then(function(userList){
        vm.users = userList;
    });
}

function deleteUser() {
    service.deleteUser(user).then(function(){
        activate();
    });
}

Finally, here is the service code:

function deleteUser(user) {
    var index = userList.indexOf(user);
    if (index !== -1) userList.splice(index, 1);

    return new Promise((resolve, reject) => {
        resolve(userList);
    });
}

After deleting a user, the service is called and upon completion, it activates the activate() function. This updates vm.users, but not immediately in the UI. Strangely, after clicking delete a second time, it does update correctly!

What could be causing this delayed update?

Answer №1

Question: The problem you're facing is related to AngularJs not knowing when to trigger the digest cycle after completing a .then() function with non-angular promises. It only triggers the digest cycle upon return from the parent function, which happens immediately without any changes taking effect yet.

Note - This is why it works on the second click, as it triggers the digest cycle upon immediate return from the function, by which time the data has changed from the first click.

Solution: To address this issue, consider using the $q service for deferreds/promises in angularjs. This will resolve your problem since the API is very similar to that of Promise, requiring minimal changes to your existing code. Simply replace new Promise(...) with $q(...)

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

Transform json nested data into an array using JavaScript

Can anyone assist me in converting Json data to a Javascript array that can be accessed using array[0][0]? [ { "Login": "test1", "Nom": "test1", "Prenom": "test1p", "password": "124564", "Email": "<a href="/c ...

I often find myself frustrated while using Next.js because the console automatically clears itself, making it difficult for me

I am facing an issue with my form in the Next.js app. Here is how it is defined: <form onSubmit = { async() => await getCertificate(id) .then(resp => resp.json()) .then(data => console.log(data)) }> Whenever there is an erro ...

Using a static function within a library's state function in NextJS is throwing an error: "not a function"

Inside a library, there's a special class known as MyClass. This class contains a static method named setData. The contents of the MyClass.js file are shown below: class MyClass { static DATA = ''; static setData(data) { MyClass ...

Unexpected error in log4javascript on IE8: Expected function not found

I'm attempting to redirect console calls to the log4javascript library. Essentially, any usage of console.log should trigger log.info, with log being an instance of Log4javascript. However, when log.info is invoked, I encounter a "Fonction attendue" ...

What steps can be taken to prevent the "unable to convert undefined to an object" error from occurring?

There seems to be an issue with some of the documents not containing the planDetails and planId properties, resulting in the error "can't convert undefined to an object." However, I need to fetch that document whether these properties exist or not. Ho ...

The function given to requestAnimationFrame is not being triggered as expected

I have successfully implemented an infinite loop animation using setInterval. However, I want to enhance the performance by switching to requestAnimationFrame(). Unfortunately, the function supplied to requestAnimationFrame() is not being called for some r ...

Issue: Node Sass 8.0.0 is not compatible with the version ^4.0.0

I encountered an error when starting a React app with npm start. How can I resolve this issue? ./src/App.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--6-oneO ...

At what point in time is the $digest cycle invoked?

I am feeling a bit perplexed about how a digest cycle operates. Is it scheduled to run periodically at intervals of 50ms (as mentioned here and suggested here), or is it triggered after every event that enters the angular context (as explained here, here, ...

Issues arising from the lack of synchronization between the original scope and the angularJS

I am working with scope.data that contains an array of objects. The data from this array is being shown in a table ordered by the x property. While the display in the table looks good, the scope.data object itself is not sorted to match what's display ...

Ways to update an angular page using the router without resorting to window.location.reload

I have a specific method for resetting values in a component page. The process involves navigating from the "new-edition" page to the "my-editions" component and then returning to the original location at "new-edition". I am currently using this approach ...

What's the best way to show floating point numbers in a concise format while also maintaining the ability to perform calculations within this Vue app?

I'm currently developing a compact calculator application using Vue 3 and implementing some custom CSS. For the most part, everything seems to be functioning correctly, except for when the results are long numbers that extend beyond the display limit ...

Prevent further execution upon callback in an AJAX request by stopping the click event function

When the function myClick() is called within itself instead of myLoad() on the first click, it leads to double execution of myClick() on the second click. => This results in two consecutive executions of the click event for #myBtn with just one click. ...

Resolving the Smooth Scrolling Problem

Here is a simplified version of what I am currently working on: Although I have managed to get the scrolling functionality to work, there seems to be an issue with transitioning from one section to another. For example, when clicking on NUMBER 3, it s ...

Filtering Tables with AngularJS

Currently, I'm experimenting with using angularJS to filter data in a table. My goal is to load the data from a JSON file that has a structure like this (example file): [{name: "Moroni", age: 50}, {name: "Tiancum", age: 43}, { ...

Using and accessing Ajax response across all routes in an application

I am developing a Node.js Express API application that requires several AJAX calls at the start of the application for global data access in all requests. At the beginning of my app.js file, I include: var users = require('./modules/users'); I ...

When running the test, the message "Unable to resolve all parameters for BackendService" is displayed

Upon executing the ng test command, the following error was displayed. This is my service specification: describe('BackendService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ { p ...

What is the best way to modify a variable's value from a nested controller and vice versa?

There seems to be an issue with changing the 'mensaje' variable in both the "padre controller" and the "hijo controller" and visualizing the changes. When clicking on "cambiar padre," the value changes as expected. However, if I then click on "ca ...

WebAPI provides a similar functionality to an array in JavaScript through the use of IQueryable

I have a WebAPI method that returns an IQueryable of a 'complex' object in the following format: [Route("api/INV_API/deptSelect")] public IQueryable<DEPTNAME_DESCR> GetDistinctDeptSelect([FromUri] string q) { if (q != null) ...

The video on Videojs fails to show up on the screen

Currently utilizing the most recent version of videojs. Referencing this example http://jsfiddle.net/swinginsam/NWbUG/#share Access source code Having trouble identifying the issue. <!DOCTYPE html> <html> <head> <title>Video.j ...

Issue with displaying multiple checkboxes using Materialize CSS in combination with Leaflet for web-mapping overlays

I'm currently using Materialize 0.97.7 along with Leaflet 1.0.1 (the latest version). <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.1/leaflet-src.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com ...