``Despite running $scope.$digest, the scope variable is failing to update in the view

.controller('PizzaCtrl', ['$scope','$state','$ionicLoading',
    function($scope, $state, $ionicLoading) {

    $scope.$emit('menu-refresh-request');

    $scope.$on('menu-refresh-response', function(event) {
        console.log("pizza");
        $scope.$broadcast('scroll.refreshComplete');
        $scope.items = $scope.$parent.menu.pizze;
        console.log($scope.items[1].price);
        $ionicLoading.hide();
    });
    $scope.doRefresh = function() {
        $scope.$emit('menu-refresh-request');
    };
}])

Everything seems to be in order. The correct data is logged successfully. But strangely, the ng-repeat="item in items" directive in my view refuses to display the pizza items.

I attempted using both $scope.$apply and $scope.$digest within the event listener, yet an error was thrown stating that a digest process was already ongoing.

It's interesting to note that this controller has two sibling controllers with similar logic, just for different menu sections. Surprisingly, the console.log("pizza") statement doesn't trigger until I navigate into the state.

Is there a specific reason why my view isn't updating as expected?

<ion-refresher pulling-text="Updating Menu..." on-refresh="doRefresh()">
<div class="list menu-list">
    <a class="item menu-item" ng-repeat="item in items" ui-sref="menu.pizza-detail({ index: $index })">
        <div class="row">
            <h3 class="row" ng-bind="item.name"></h3>
            <div class="row">
                <div class="list-price col col-15">
                    <h4 class="list-value" ng-bind="item.price"></h4>
                </div>
                <div class="list-description col col-85">
                    <p ng-bind="item.description"></p>
                </div>
            </div>
        </div>
    </a>
</div>

Answer №1

Instead of relying on $scope.$apply, consider using the $timeout service provided by Angular. Unlike $scope.$apply, using $timeout does not result in errors like "$digest already in progress". This is because $timeout informs Angular that there is a timeout scheduled after the current digest cycle, preventing any collisions between digest cycles and ensuring that the output of $timeout will be executed on a fresh $digest cycle.

.controller('PizzaCtrl', ['$scope','$state','$ionicLoading', '$timeout',
    function($scope, $state, $ionicLoading, $timeout) {

    $scope.$emit('menu-refresh-request');

    $scope.$on('menu-refresh-response', function(event) {
        console.log("pizza");
        $scope.$broadcast('scroll.refreshComplete');

        $timeout(function(){
             $scope.items = $scope.$parent.menu.pizze;
        });
        console.log($scope.items[1].price);
        $ionicLoading.hide();
    });
    $scope.doRefresh = function() {
        $scope.$emit('menu-refresh-request');
    };
}])

Answer №2

After a thorough investigation, it was revealed that the solution to this particular issue was as simple as adding a closing tag to the <ion-refresher> element.

<ion-refresher pulling-text="Updating Menu..." on-refresh="doRefresh()"></ion-refresher>
<div class="list menu-list">
    <a class="item menu-item" ng-repeat="item in items" ui-sref="menu.pizza-detail({ index: $index })">
        <div class="row">
            <h3 class="row" ng-bind="item.name"></h3>
            <div class="row">
                <div class="list-price col col-15">
                    <h4 class="list-value" ng-bind="item.price"></h4>
                </div>
                <div class="list-description col col-85">
                    <p ng-bind="item.description"></p>
                </div>
            </div>
        </div>
    </a>
</div>

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

Remove a div element with Javascript when a button is clicked

I am working on a project where I need to dynamically add and remove divs from a webpage. These divs contain inner divs, and while the functionality to add new divs is working fine for me, I'm facing some issues with removing them. The code snippet b ...

Transform an array into an object with assigned key names

How can we transform the following array: [2019,2020,2021] into the format: { 0: {year:2019}, 1: {year:2020}, 2: {year:2021} } ...

unusual occurrences with JavaScript - debugging on Google Chrome

There's a bizarre issue happening in my code. An object is being sent correctly by the server, and it's arriving in my angular factory just fine. However, when I log the object, something strange occurs: https://i.sstatic.net/S6WvC.png When the ...

Disable the rotation animation on the Three.js cube

I've successfully created a 3D wireframe cube using Three.js examples, however, it's continuously rotating, I'm looking to halt this animation. When I remove the animate(); function at the end of the script, the Canvas fails to load. // s ...

Adjustable dimensions and the AngularJS framework

Upon page load, a directive is triggered to resize the content to fit within the correct dimensions. However, there seems to be an issue when a service call populates the model of a specific section of content after the resizing has taken place. The elemen ...

Different ways to loop through varying grid dimensions

I'm struggling to find a solution to the following problem: I have 5 grids in a row with sizes md={2}, md={3}, md={2}, md={2}, md={3} Now I need to loop through them, but since the grid sizes are different, how can I manage them? <Grid item xs={ ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

Is there a way to ensure my fetch request is only triggered once within a React Component?

I am trying to fetch an object and extract a URL from it, but for some reason my console.log is being repeated 8 times. Can anyone spot where I might be going wrong? import React from 'react'; // import Card from './Card'; function Gam ...

How can I use jQuery UI to slide a div, while also smoothly moving the adjacent div to take its place?

Wishing you an amazing New Year! I am looking to create a smooth sliding effect for a div when a button is clicked. I want the adjacent div to slide alongside it seamlessly, without any clunky motions or delays. Currently, the adjacent div only moves afte ...

"How to dynamically fill a text input field from a table using jQuery when a specific value is selected, potentially involving multiple rows (possibly

Scenario I created a form that allows users to place orders for articles. These articles are displayed in a table within another form, where each article is listed with its code, description, and price. The goal is for users to select an article from th ...

Halt the execution of code once the user unselects the div

Is there a way to prevent the setInterval function from running when the user unselects the div they originally selected? I've tried using clearInterval but it's not working. Also, utilizing the cvalue from this doesn't seem to update within ...

The retrieved JPEG data from FileReader does not align with the actual data stored in the file

My goal is to choose a local JPEG file in the web browser using HTML5 FileReader so that I can submit it to a server without having to reload the page. Although all the technical aspects are functioning properly and I believe I am successfully transferring ...

Node.js failing to log chat messages

The goal is to log the chat message entered by the user in the console (terminal). Currently, there seems to be an issue with logging and I'm struggling to debug it. Keep in mind that I am a novice when it comes to NodeJS and only have basic knowledge ...

Avoiding unnecessary DOM updates in VueJS

Implementing an animated carousel has been my latest project, and I've been using code similar to the following: <template> <div v-for="(slides, id)" v-if="id > middle_id - 2 || id < middle_id + 2"> <div :class ...

Unusual express middleware usage in NodeJS

app.use(function(req,res,next){ console.log('middleware executed'); next(); }); app.get('/1',function(req,res){ console.log('/1'); res.end(); }); app.get('/2',function(req,res){ console.log('/2'); res.end() ...

The JQuery functionality is failing to execute properly on Internet Explorer

I have developed a JQuery script that appears to be working perfectly in all browsers, except for IE 8. Interestingly, when I checked Internet Explorer's error details, it did not provide any specific information about the issue. Instead, IE simply po ...

The $scope.$watch function doesn't trigger even though there have been changes in

My $watch function is not being triggered when the loadStats method in vm is called var vm = this; vm.loadStats = function(){ vm.propositions = null; DateUtils.convertLocalDateToServer(vm.startDate); vm.endDateServer = DateUtils.convertLocalDate ...

Using an Ajax Post Call to send FormData leads to a Get request instead

Having trouble with sending a simple form via POST method. I load the form content using AJAX: $(function() { var arg = { "operation": "upload", "step": "0" ...

What is the best way to modify Mega Menus using JavaScript?

I am currently managing a website that features "mega menu" style menus. These menus consist of nested <UL> elements and contain approximately 150 to 200 entries, resulting in a heavy load on the page and posing challenges for screen readers. To add ...

Retrieving the final object from an express query

Sorry if this question sounds silly, but I'm new to working on the "backend" of things. I have this code snippet below and I'm facing an issue where calling fetchSum() successfully sends data to the server, but upon returning to the client, it th ...