AngularJS framework may encounter an issue where changes in $scope data do not reflect in the view

I have noticed that when I reload the data using my function, the view does not change. After some research, I found that adding $scope.$apply() should solve this issue. However, I am encountering an error when trying to implement this solution.

https://docs.angularjs.org/error/$rootScope/inprog?p0=$apply

This is my script:

var roomsApp = angular.module('roomsApp', []);
roomsApp.controller('RoomListController', function RoomListController($scope, $http) {
    $scope.refreshData = function () {
        $http({
            method: 'GET',
            url: '<?=url('getRooms')?>'
        }).then(function successCallback(response) {
            $scope.rooms = response.data;
            console.log(response);
        }, function errorCallback(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        });
    }
    $scope.refreshData();

    $scope.addRoom = function (title) {
        if (title != "" && typeof title !== 'undefined') {
            $http({
                method: 'POST',
                url: '<?=url('addRoom')?>',
                data: {
                    title: title
                }
            }).then(function successCallback(response) {
                $scope.refreshData();
            }, function errorCallback(response) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            });
        }
        $scope.$apply();
    };
});

This is my Angular-HTML code:

<div class="row" ng-app="roomsApp">
    <div class="col-md-8">
        <div class="panel panel-default" ng-controller="RoomListController">
            <div class="panel-heading">Rooms</div>
            <div class="panel-body">
                <ul class='list-group' ng-repeat="room in rooms">
                    <li class="list-group-item">{{room.title}}</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="panel panel-default" ng-controller="RoomListController">
            <div class="panel-heading">New room</div>
            <div class="panel-body">
                <div class="input-group input-group-lg">
                    <span class="input-group-addon" id="title">Title</span>
                    <input type="text" ng-model="title" class="form-control" placeholder="" aria-describedby="title">
                </div>
                <br>
                <button ng-click="addRoom(title);" type="button" class="btn btn-primary pull-right"><span
                        class="glyphicon glyphicon-plus"></span></button>
            </div>
        </div>
    </div>
</div>

Answer №1

Here is a suggestion for you:

$apply(function(){
    rooms = dataFromResponse;   
});

Answer №2

  1. Eliminate the need for $scope.$apply();
  2. In your HTML code, delete both instances of
    ng-controller="RoomListController"
  3. Place
    ng-controller="RoomListController"
    on the
    <div class="row" ng-app="roomsApp">

Explanation: Your current implementation is causing issues because it establishes two independent scopes for RoomListControllers. This setup prevents proper communication between the controllers when you try to update the list in one controller while executing the addRoom method in the other. As a result, the controllers cannot interact with each other effectively.

p.s. If you require two distinct controller scopes, consider using the rootScope.broadcast - rootScope.on pattern to facilitate communication between the sibling scopes.

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

The TouchableOpacity function is triggered every time I press on the Textinput

Every time I press on a text input field, the login function is called This is the touchable statement: <TouchableOpacity style={InputFieldStyle.submitButton} onPress={this.login(this.state.email, this.state.password)}> <Text ...

Encountered an npm ERR while executing the React project

I'm encountering an issue with running my React project. When I use the command "npx start", I receive the following error message. Can someone please assist me with this? npm ERR! could not determine executable to run npm ERR! A detailed log of thi ...

Navigating to Protected Mobile Platform

I am experiencing an issue with accessing a .NET website with SSL on my Blackberry device. When I try to view the site, I receive the message "HTTP ERROR 403 FORBIDDEN - You're not authorized to view this page. Please try loading a different page". Th ...

Encountering a problem involving the apostrophe character "'" when trying to save content into a MySQL database

I have been developing an application that allows users to create HTML templates and save them. Users can utilize different components such as text, images, etc. to build HTML pages. Challenge: The issue I'm encountering is when a user inputs text wi ...

Issue with AngularJS controller method not functioning properly when assigned to a Div

I am facing an issue with a login form and its controller. The login function is not triggering upon submitting the form for some reason. Here is the code snippet for the form within the larger view file: <div class="login-wrap" ng-controller="LoginCt ...

Conceal the block quotes while substituting with a newline

My HTML page contains numerous comments enclosed in blockquotes. I attempted to implement a feature that allows users to hide all the comments with just one click by using the following JavaScript code: const blockQuotes = document.getElementsByTagName(& ...

Converting Blob to File in Electron: A step-by-step guide

Is there a way to convert a Blob into a File object in ElectronJS? I attempted the following: return new File([blob], fileName, {lastModified: new Date().getTime(), type: blob.type}); However, it appears that ElectronJs handles the File object differently ...

Highlighting the current menu item by comparing the URL and ID

Looking to make my navigation menu items active based on URL and ID, rather than href. None of the suggested solutions (like this one, this one, or this one) have worked for me. This is how my Navigation is designed: <nav id="PageNavigation"& ...

Activate the date-picker view when the custom button is clicked

Utilizing this library for date-picker functionality has been quite beneficial. I am currently working on a feature that involves opening the date-picker upon clicking a custom button. The default input is functioning properly. <input name="pickerFromD ...

Algorithm to identify the highest sum of two numbers in a disorganized array of whole numbers

I am looking to create a function that can identify the largest pair sum in an unordered sequence of numbers. largestPairSum([10, 14, 2, 23, 19]) --> 42 (sum of 23 and 19) largestPairSum([99, 2, 2, 23, 19]) --> 122 (sum of 99 and 23) largestPairSum ...

Problem with finding Rails controller file in .coffee extension

I recently started learning Rails and came across a file called welcome.js.coffee in the assets javascripts directory. # Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in applica ...

What are the best practices for presenting Motion JPEG binary data streams using Angular, Ionic, and JavaScript?

I am developing an application for a device that will receive a POST request and send back a binary data stream in the format of multipart/x-mixed-replace. My goal is to display this stream on a specific section of my app's homepage. After conducting ...

What is the outcome of XmlHttpRequest.responseText?

I am new to JavaScript and looking to explore the potential of XMLHttpRequest.responseText with a specified URL. Can someone guide me on how to efficiently test this? let url = "http://m.google.com/"; <br> let xmlHttp = new XMLHttpRequest(); <br& ...

Angular Components unexpectedly lose background transparency when using Transparent-Background-PNG in the foreground

Hey there! I'm currently working on a landing page and I have this amazing idea to use a stunning picture of clouds with a transparent background layered over a beautiful landscape. The only problem is that when I try to implement it, the transparency ...

Utilize Vue: Bring in the router within a helper class and navigate to a specific

I'm new to utilizing Vue, and I am currently attempting to import my existing router instance into a JavaScript class where I manage the Authentication. This is the content of my router file: import Vue from 'vue'; import Router from &apos ...

The addition of a slash between the hashtag and the anchor name by Fullpage.js is causing conflicts with ng-include

My experience with using fullpage.js on a simple site alongside angular directives has been met with an issue. When including a .phtml file, the anchor functionality of fullpage.js stops working as it adds a slash before and after the anchor name. UPDATE ...

How can I prevent media controls from appearing in fullscreen mode on Microsoft Edge using CSS?

My video code allows for switching the video into fullscreen mode using custom controls. Here's how it looks: fullScreenButton.addEventListener("click", function() { if (video.requestFullscreen) { video.videoContainer.r ...

Transform variable names from Java and AngularJS conventions to standard English

In my quest, I have successfully used JAVA Reflections to extract attribute names from a class. However, I desire to change the variable naming convention, such as transforming firstName into First Name. I currently contemplate utilizing the .split() meth ...

Implementing $timeout within the Scope.$watch function allows for monitoring

Hi there, I'm currently working on implementing some functionality in Angular but running into a few issues. I have an ng-model and example-directive configured as follows: <input ng-model="model" type="text" class="form-control"> <div ex ...

Navigate within the div by scrolling in increments of 100%

I am facing an issue with a div that contains multiple children set to 100% height. My goal is to scroll exactly the height of one child (which is also 100%) on each scroll. However, I am struggling to prevent scrolling multiple steps at a time. I have tri ...