Angularjs fails to refresh $scope changes

I'm facing an issue with my controller where the Gui $scope is not updating properly. After conducting some research, I discovered that using $timeout could potentially help.

The service's processing time varies on different units and setting a fixed 5000 timeout seems to slow down the app. Are there any alternative methods to accomplish this?

.service('RowService', function ($q) {

var rows = undefined;
this.getrows = function (id) {
  var local = new PouchDB('db');
  var deferred = $q.defer();
  //      var rows = [];
  local.query(function (doc, emit) {
    emit(doc.type);
  }, { key: 'row_detail' }).then(function (result) {
    var rows = [];
    for (i = 0; i < result.rows.length; i++) {
      local.get(result.rows[i].id).then(function (response) {
        if (response.orderid == orderId) {
          rows.push(response);
        }
        deferred.resolve(rows);
      })
    }
  }).catch(function (err) {
    // handle any errors
  });

  rows = deferred.promise;

  return $q.when(rows);
}

})


RowService.getrows($stateParams.id).then(function (data) {

    // Non-functional example
    $scope.rows = data;
    // Functional example

  $timeout(function () {
    $scope.rows = data;
  }, 5000)

}

Answer №1

While $scope.$apply() may have its challenges, invoking $timeout does not require any delay:

.service('RowService', function ($q) {

var rows = undefined;
this.getrows = function (id) {
  var local = new PouchDB('db');
  var deferred = $q.defer();
  //      var rows = [];
  local.query(function (doc, emit) {
    emit(doc.type);
  }, { key: 'row_detail' }).then(function (result) {
    var rows = [];
    for (i = 0; i < result.rows.length; i++) {
      local.get(result.rows[i].id).then(function (response) {
        if (response.orderid == orderId) {
          rows.push(response);
        }
        deferred.resolve(rows);
      })
    }
  }).catch(function (err) {
    // handle any errors
  });

  rows = deferred.promise;

  return $q.when(rows);
}

})


RowService.getrows($stateParams.id).then(function (data) {

    // Not working example
    $scope.rows = data;
    // Working example

  $timeout(function () {
    $scope.rows = data;
  })

}

Answer №2

If you omit the timeout value, the function will execute after all other functions have completed. Additionally, since you are utilizing promises in your service, a timeout value is not necessary.

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

Terminating a client connection in Node.js using socket.io

What is the best way to terminate the socket connection on the client side? I am currently utilizing: socket.io 0.9 node.js 0.10.15 express 3.3.4 For example, when calling localhost/test -- server side var test = io .of('/test') .on(&apos ...

Tips for prioritizing new data input at the top of the list

Hey there, I'm having trouble figuring out how to push new data to the top of a list using vue.js and laravel. I've been trying but haven't had any luck so far. If anyone could lend a hand, I would greatly appreciate it. Below is my Control ...

Tips on updating arrow button icon when clicked using jquery

I am currently working on a project where I have a button icon that I want to change upon clicking it. I am using the following jQuery code: <script> $('div[id^="module-tab-"]').click(function(){ $(this).next('.hi').sl ...

How can I display a spinner/loader gif when the page loads using Vue?

When it comes to loading components on a webpage, jquery has the options of $( document ).ready() and onload. But in Vue, how can we achieve the same effect? For example, when a user clicks our page, how can we display a spinner until all contents are load ...

How can I make the Box div bigger or smaller?

My goal is to expand and collapse the slider div only for the box where the user clicks. I have achieved this functionality, but a problem arises when I click "read more" - all the boxes expand, which is not the desired behavior. I want only the specific b ...

Activate Gulp watcher to execute functions for individual files

I have developed a specific function that I need to execute only on the file that has been changed with gulp 4.0 watcher. For example, the current task setup looks like this: gulp.watch([ paths.sourceFolder + "/**/*.js", paths.sourceFolder + "/**/ ...

Discover similarities between two arrays

My goal is to compare two arrays and generate a JSON array marking true if there's a match and false if there isn't. The second array will always have values that match some from the first, and it will be smaller as it's derived from the fir ...

Tips for executing a loop while waiting for a jQuery ajax request to complete

I currently have this code setup: for (var i = 0; i < $total_files; i++) { $.ajax({ type: 'POST', url: 'uploading.php', context: $(this), dataType: 'json', cache: false, contentType: false, pr ...

Transfer PHP variables into a JavaScript array for dynamic data population

Similar Question: Dynamic Pie Chart Data in Javascript and PHP This snippet of code is utilized for populating a pie chart using javascript: <script type="text/javascript"> var agg = { label: 'Aggressive', pct: [60, 10, 6, 30, 14 ...

Sending data from HTML and JavaScript to Python

In the process of developing a website that will operate on an embedded device, I am implementing an interface for users to engage with multiple functions on the site. These functions within the HTML interface will communicate with a Python script, which i ...

Enhancing Form Validation with Vuejs 2

With vue-validator being prepared for Vuejs 2, what is the most effective method for implementing frontend validation? UPDATE I've come across a fantastic plugin called Vee Validate ...

Every time I try to access Heroku, I encounter an issue with Strapi and the H10 error code

Upon opening Heroku and running the command "heroku logs --tail", my app encountered a crash and I can't seem to locate my Strapi application in Heroku. 2020-05-04T19:05:38.602418+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GE ...

Accessing form data within Mongoose schema hooks via JavaScript

I have a form where I've split the content into two separate MongoDB schemas. I want to access variables that are within node.js/express.js directly in mongoose schema hooks, whether through pre or post hooks of the schema. Here are my files: expres ...

Updating the jQuery AJAX URL dynamically based on user input in a form submission

Exploring the world of AJAX and form submission, I find myself in need of assistance. My webpage is designed to display real-time stock market data, updating fields with the latest price, change, high, low, and more. I am currently attempting to modify th ...

Empty form field when submitting form using ajax in C# MVC

I am encountering an issue while attempting to store form data in a database using $.ajax. The problem lies in the fact that upon submitting the form, the username is being saved as null, whereas the email and password are correctly stored. function Sav ...

Adjust the styling of selected elements when their values are changed

I am attempting to modify the background color based on the selected value that is returned. However, my current code doesn't seem to be working as expected: <script> $(document).ready(function() { $('#assessments').change(functi ...

What is the best way to add a new row to an existing CSV file using json2csv in Node.js?

I need to append a new row to an existing CSV file. If the CSV file already exists, I want to add the new row after the last existing row without adding a column header. Here is the code snippet that I have been using: var fields = ['total', &a ...

Adjust the scroll bar to move in the reverse direction

I'm trying to modify the behavior of an overlay div that moves when scrolling. Currently, it works as expected, but I want the scroll bar to move in the opposite direction. For example, when I scroll the content to the right, I want the scroll bar to ...

Utilize the directive method within the transcluded content by making a call

Trying to call a method within a directive from transcluded content. The structure of my HTML is: <typeahead class="typeahead" model="customers" filtered-model="customersfiltered" ng-model="selectedcustomer"> <ul> <li ng-click="select ...

What is the reason for the event object not being included in the window object's prototype?

I'm finding it difficult to wrap my head around the element and event objects in my studies. I know that JavaScript has a global window object, as well as four other built-in objects: Math, String, Array, and Date. Is it accurate to say that the docum ...