Updating Angular JS views in real-time using database changes

I am currently in the process of building a social networking application using AngularJS. I have come across an issue regarding data binding. In my app, there is a timeline div where all the recent posts are displayed, along with a status updater at the top. Upon page load, I make an AJAX ($http) call to the database to retrieve all the posts in JSON format and bind them to the div using ng-bind. However, if I update the status, how can I ensure that the updated data is displayed without having to refresh the entire page? I'm struggling with this problem and would appreciate any assistance.

Thank you, Pavan

EDIT## - Some helpful individuals requested for code, so here it is. I am still encountering difficulties in properly binding my JSON data. Your guidance is highly appreciated.

wall.controller('mainData', function($scope, $http)
{
$scope.status = {};
$scope.updatedStatus = {}; 
$scope.getStatus = function(){
  var uid = localStorage.getItem('_id');

    $http({
        method: "GET",
        url: "http://localhost:8000/profile/status/"+uid


    }).success(function (data, status, headers, config) {

        $scope.updatedStatus =data;            

    })

}

and the HTML section

 <div class="card" ng-controller="mainData"  ng-repeat="item in updatedStatus">
                            <div class="card-header">
                                <div class="media">
                                    <div class="pull-left">
                                        <img class="lv-img" src="img/profile-pics/2.jpg" alt="">
                                    </div>

                                    <div class="media-body m-t-5">
                                        <h2><a href="profile.html"       class="a-title">{{item.firstname+" "+item.lastname}}</a><small>{{item.record_time}}</small></h2>
                                    </div>
                                </div>
                            </div>
                            <hr/>
                            <div class="card-body card-padding">
                                <p>{{item.message}} </p>

                            </div>

                        </div>

JSON array received from the server

[
{firstname: "Pavan"
id: 1
lastname: "Kumar"
message: "This is my first update"
record_time: "10/16/2015, 8:32:16 PM"},
{firstname: "LOL"
id: 2
lastname: "test"
message: "This is my second update"
record_time: "10/16/2015, 8:32:16 PM"}
]

Despite receiving a valid JSON object from the server, I am unable to display any new values added or existing data. There seem to be issues with the ng-repeat directive. Any help on resolving this matter would be greatly appreciated. :)

Answer №1

There are three places where your data exists:

1. The database

2. The JavaScript object

3. The HTML view

If you bind the value in the JavaScript object, it will be the same as the one in the HTML view. If you change the value in the JavaScript object, it will also be changed in the view.

In your question, you mentioned that:

I fire an AJAX($http) service to the DB

If you are using Angular $http service or another similar one, there should be no issue. However, if you are using a non-Angular function for the HTTP request, make sure to call this function at the end of the callback function:

$scope.$apply();

This will prompt the digest loop to work and apply your changes on the view.

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

Is it necessary for a click handler to be triggered when clicking on a scrollbar?

Check out these HTML snippets: Jsfiddle <style> div { margin:20px; border: 30px red solid; padding: 20px; background-color:green; overflow-y:scroll; } </style> <div onclick="alert('div clicked');"> ...

Having trouble grasping the error message "Uncaught Typerror Cannot Read Property of 0 Undefinded"?

As I embark on creating my very first ReactJS website with Node in the back-end, I encountered an issue in fetching and printing data. While I successfully displayed the names, pictures, and emails of project members from the server, I faced an error when ...

What is the best way to prevent two paths within an SVG from intersecting with each other?

Currently, I am developing a program that allows the user to draw lines. Once the user completes drawing a line, I receive an array of points in this format: [[x, y], [x, y], ...]. I then convert these points into a path string using the following functio ...

Getting information from a PHP script using jQuery AJAX with the (webpack based) ZURB Foundation Framework

Currently, I am working on a ZURB Template project that was set up using the foundation client. As part of my work, I have already completed some initial tasks such as enabling ES7 features async/await in Babel7 (ZURB Foundation utilizes gulp as taskrunner ...

Why is a <script> tag placed within a <noscript> tag?

Lately, I've been exploring various websites with unique designs and content by inspecting their source code. One site that caught my attention was Squarespace, which had blocks of <script> tags within a <noscript> tag: <!-- Page is at ...

How to Animate an Object's Rotation Gently using React Three Fiber App and Use Cannon Library?

I am currently working on a project to create a Tetris-like game using React app, react-three-fiber, and use-cannon. I would like to implement a feature where objects/meshes rotate smoothly when clicked. How can I achieve this? Here is the code for the ob ...

Nuxt's dynamic route generation results in a 400 error status code

Currently integrating Nuxt with my app and aiming to establish a connection with my server to retrieve data. To create dynamic routes, I am utilizing the built-in generate method but facing some challenges. Upon executing the generate command, I encounte ...

Can Jquery be utilized to signal a language change?

I'm working on my portfolio website that will be available in two languages, Thai and English. I have successfully implemented language buttons for changing between the two languages. However, I am facing an issue with the language selection when nav ...

Whenever I make an AJAX call to update the queryset in my child template, the javascript suddenly ceases to function properly

I am using a comments.html child template with the following structure: <div class="commentsContainer"> {% for comment in comment_list %} ... {{ comment.text }} ... {% endfor %} </div> Whenever I click on a bu ...

Using AJAX to create an interactive dropdown menu with changing options

I have been working on creating a dropdown menu using Ajax. When hovering over the navigation bar, the menu successfully triggers the Ajax function to display the dropdown options. The issue arises when attempting to navigate to another page (show_activi ...

Utilizing Typescript to implement an interface's properties

After declaring an interface as shown below interface Base { required: string; } I proceeded to implement the interface in a class like this class MyClass implements Base{ method(): void { console.log(this.required); } } However, I ...

Is the user currently browsing the 'Home screen webpage' or using the Safari browser?

In JavaScript, is there a method to determine if the user has accessed the website from their home screen after adding it to their home screen, or if they are browsing via Safari as usual? ...

Express Session Issue Preventing Ajax Call from Functioning

After testing the /temp route directly in the browser and then through an ajax call to the /test route, I noticed a difference in the session information. When accessed directly, the session retains the data added via the /temp route, but when called throu ...

Ways to properly close open HTML tags using node.js?

Have you ever encountered a situation where user-entered content from a database or similar source only contains the opening tag without the closing tag? This can disrupt the layout of your website. Is there a way to fix this issue using Node.js on the s ...

Manipulating the background-image in CSS using AngularJS is a breeze

In my design, I have a specific style applied to list items with a default background image: .defaultListItem > .item-content { background: linear-gradient(rgba(0, 0, 0, 0.1),rgba(0, 0, 0, 0.2),rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.7)), url('.. ...

Ionic (Angular) experiencing crashes due to numerous HTTP requests being made

My template contains a list of items <ion-list class="ion-text-center"> <div *ngIf="farms$ | async as farmData"> <ion-item (click)="selectFarm(farm)" *ngFor="let farm of farmData" detail=&quo ...

I need help figuring out how to navigate between different pages in my Vue-cli app that has multiple pages configured

After following the guide on https://cli.vuejs.org/config/#pages, I successfully configured vue-cli3 to build a multiple page application. My project consists of 2 static pages, and I set up the vue.config.js file as shown below. However, when running the ...

HTML - Transforming JSON data into a table

I'm having trouble converting JSON data into a table format. Although everything seems to be in order, I am unable to view the values on my table. Here is the code I am using to convert JSON to a table: $(function() { var my_data = &ap ...

Duplicate values of React object properties when using .push method within a loop

In my code, I've implemented a function called handleCreate that is responsible for taking user data and inserting it into a database. Within the loop of aliasArr.forEach(), I am sending new user instances to my database for each element in the alias ...

Struggling with making react-hook-form correctly validate an email address

I've been struggling for a long time to make this validation work correctly, but it seems impossible. I even added some text at the bottom to display an error message related to the email, but it always shows no error, regardless of the situation. Ed ...