Angular.js fails to update the repeater when $scope.var is modified, only refreshing after a manual refresh

I always thought two-way binding was just an Angular thing:

When I submit a form to the controller, my input is displayed on the page. However, I have to refresh the page to see the new input:

$scope.loadInput = function () {

    $scope.me.getList('api') //Restangular - this part works
    .then(function(userinput) {

        $scope.Input = $scope.Input.concat(userinput);
        // scope.input is being referenced by ng-repeater in the page 
        // so after here a refresh should be triggered.

    },function(response){
        /*@alon TODO: better error handling than console.log..*/
        console.log('Error with response:', response.status);
    });
};

The HTML page uses ng-repeater to loop through the array with for i in input, but the new input from the form is only displayed after refreshing the page.

I would appreciate any help with this issue - thank you!

Answer №1

Implement $scope.$apply:

$scope.loadInput = function () {
        $scope.me.getList('api') //Restangular - this part works
        .then(function(userinput) {
               $scope.$apply(function(){ //notify angular of the changes

                $scope.Input = $scope.Input.concat(userinput);
             });

            },function(response){
                /*@alon TODO: improve error handling instead of console.log..*/
                console.log('Error with response:', response.status);
            });
    };

The reason: Your ajax call is asynchronous, it will be executed in the next cycle, but by then, you have already exited the angular cycle. Angular is unaware of the changes, hence we need to use $scope.$apply to re-enter the angular cycle. This situation differs slightly from using services like $http from angular, where changes are automatically detected when handled within .success.

DEMO that demonstrates the issue. The initial click does not refresh the view.

setTimeout(function(){
             $scope.checkboxes = $scope.checkboxes.concat([{"text": "text10", checked:true}]);
         },1);

DEMO showcasing the use of $scope.$apply for correct behavior

setTimeout(function(){
            $scope.$apply(function(){
         $scope.checkboxes = $scope.checkboxes.concat([{"text": "text10", checked:true}]);
            });
        },1);

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

Utilizing Visuals from a Vue Component Collection

As I attempt to publish a Vue library to npmjs, I encounter an issue with the images within it. After publishing the app to NPM and importing it into my main app, everything appears to be working correctly. However, the paths to the images in the library ...

An issue arose when trying to display React components within an Angular application

Attempting to incorporate React components into an Angular 7 application has been a challenge for me. While I have successfully rendered simple React components, I encountered the following error message (displayed in the browser console) when attempting t ...

How can mongoose be used to modify user information in a database?

Hey there, I'm currently working on a personal project and came across an issue. I've successfully set up my (steam) user data to save in mongodb through mongoose. Right now, I have it set to only save a new user if they are not already in the da ...

What are the steps to launching a node.js application on CyberPanel?

I have a node.js application developed and running on my server with cyberpanel installed. While I have found numerous examples of how to deploy a node application in cyberpanel, I am unsure about how to access it from the browser. Currently, my vHost con ...

The Bootstrap navigation pills do not function properly when using a forward slash in the tab link

I am currently working with Bootstrap and using nav pills. I have noticed that if I include a / sign in the link of a tab, it causes that specific tab to malfunction and triggers a JavaScript error in jQuery's own code when clicked on. How can I go ab ...

Mongoose sparks a confrontation following the preservation of a single document in the database

I'm struggling to understand what minor mistake I'm making in this code. I have simplified the user schema to just one property, which is name. Initially, when I post the first entry to the database, it gets saved without any issues. However, whe ...

Plotly: maintaining consistent color scheme across identical elements in multiple graphs

I am currently utilizing Plotly in Javascript to generate some interactive graphs. My goal is to create 2 pie charts that display the distribution of a sale based on A) units and B) value. While I am able to generate the plots successfully, I have notice ...

Dividing AngularJS Module Components into Separate Files

I've been working on developing an AngularJS application and I'm currently facing a challenge in creating a reusable module that can be integrated into other projects. The module consists of services and directives that are distributed across sev ...

Restoring the position of the <Rect/> element after dragging in a React + Konva application

In my attempt to make a Rect component snap back to its original position using ReactKonva, I defined a Toolbar class with certain dimensions and initial positions for the rectangle. However, after dragging the rectangle and attempting to reset its positio ...

NodeJS - The function app.listen is not defined in this context

I've come across a similar question before, but the answers provided didn't help me resolve my issue. The error message I'm getting is "TypeError: app.listen is not a function"; Here's my full code below. Thank you in advance for your ...

A guide to sorting an object with integer keys by its values using JavaScript

I am facing an issue with sorting a map by values instead of keys. No matter what I do, it always ends up getting sorted by the keys. On the server side, I have a map that is already sorted. When I send this map to JavaScript using JSON, it gets re-ordere ...

Swapping JSON: A Quick Guide

When my Angular code loads, a list of buttons (button 1, button 2, button 3, etc.) is displayed. Upon clicking any button, the console shows J-SON with varying values. Two additional buttons are present on the page for moving up and down. My dilemma arise ...

Looking for assistance with JQuery and JavaScript?

I oversee a team of employees, each with a 7-day work schedule. To streamline the process, I have developed a PHP form that I would like to use to collect data for verification in JavaScript before submitting it to an SQL database using AJAX. My main cha ...

Conceal Navigation Panel while Scrolling Down, Reveal when Scrolling Up, Compatible with Chrome, Incompatible with Safari (on smartphones

I have implemented a code to hide my navbar when scrolling down and show it when scrolling up. This code works perfectly on desktop and in all browsers, including Chrome on mobile (iPhone). However, in Safari, the navbar sometimes shows, hides, and shows a ...

Should I refrain from storing user files on my server?

Greetings! I am currently working on an Express js + React js application and using MySQL for database management. I have successfully stored user information like email, hashed passwords, and user IDs in the database. However, now I want to create ...

How can I generate rotating images using jQuery or JavaScript similar to the one shown here?

http://www.example.com/ On a website similar to example.com, I noticed that when hovering over one of the topics listed, the image rotates. I am interested in creating this interactive effect using either jQuery or JavaScript. Is there a method to access ...

Oops! Looks like there's an issue with the NextJS Custom Carousel bug. The error message reads: ReferenceError: document is not defined and is unable to read properties of undefined (

I have developed a unique carousel component to showcase text testimonials from scratch. The custom carousel utilizes a specialized script, carouselFunction.js, for navigational functionality to cycle through each testimonial. Here is an image of the carou ...

X-ray Picker failing to retrieve a value

I am currently using the most recent version of the x-ray npm module in the code snippet below. Despite my expectations, the Meta and Metatags elements remain empty when I print out obj. Can anyone help me identify what I might be missing? var Xray = req ...

Why is my event.target.value not updating correctly in React useState?

My problem is that when I use useState, I am receiving incorrect numbers For example, if I print e.target.value it might display 1, but my selectedIndex shows 2. Similarly, when I have a selectedIndex of 0, it retrieves something different like 1. Any tho ...

Unable to decrease the width of a div element in Vuetify and Nuxt

As I work on creating a dynamic form with fields that need to occupy only 50% of the size of a regular field, I encounter different components based on data provided by Vuex. The use of v-for in Vue.js helps me loop through form objects and render the app ...