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

Encountering a problem while retrieving JSON or XML data from a URL using jQuery AJAX

Here is a snippet of code that I've been working on: jQuery(document).ready(function(){ var user_key = "asdflk134"; var app_key = "pigasdb95r91bva"; var params = "app_key="+app_key+"&user_key="+user_key+"&format=xml"; jQuery ...

The designated type member is not compatible with LINQ to Entities. Utilizing JSON, KendoUI, and AJAX

Hello everyone, thank you for taking the time to assist me. I'm currently exploring KendoUI and attempting to bind a Grid using AJAX, but I encountered an error: The specified type member 'getFullName' is not supported in LINQ to Entities. ...

Saving the execution of a function within an array

Creating a JavaScript program where function calls that generate 3D objects will be stored in an array is my current project. Specifically, I aim to include the following function calls: draw_cylinder(0,0,3,2); draw_sphere(0,0,5,3); draw_cone(17,0,7,3); d ...

Setting the current time in an Animation using ThreeJS

I'm utilizing skinning and skeletal animation within ThreeJS. My goal is to navigate through an animation by moving backward and forward, as well as jumping to specific locations within the sequence instead of the usual looping behavior. The animatio ...

Custom Email Template for Inviting Msgraph Users

I'm currently exploring the possibility of creating an email template for the MS Graph API. I am inviting users to join my Azure platform, but the default email they receive is not very visually appealing. public async sendUserInvite(body: {email: < ...

Can anyone identify the result produced by this line of code? Utilizing the $.get method to access "http://192.168.4.1:80/" with the parameter {pin:p}

Can anyone explain the output of this line of code? $.get("http://192.168.4.1:80/", {pin:p}); I understand that it is an Ajax code that sends data through a GET request, but I am trying to manually send the same data like this ".../pin:13" or "", however ...

AngularJS directive facing a callback problem

Having trouble with callbacks while calling a service function This is the function defined in registrationService function checkUserAccess(incentiveLevel, callback, displayRegistrationView) { var url = "..."; httpWrapperService. ...

Using AngularJS to bind the ng-valid attribute to a JavaScript function

Hey there! I am interested in setting the validity of an input field using an expression, but not a regular expression. I would like to do something similar to this: <input ng-model="number" required ng-valid="number / 2 > 14"> Is it achievable? ...

Avoiding Duplicate Form Submissions Without JavaScript

Currently, I am working on a project where I am implementing the MVC pattern. Upon successful submission of a form, I redirect the user and display a flash message indicating success using session data. Users face no issues when using the back button or re ...

Tips for incorporating a plugin and utilizing an external module or file on RT

My node.js application/module is currently functioning well with a plug-in concept. This means that my module acts like a proxy with additional capabilities, such as adding new functionality to the existing methods. To achieve this, follow these steps: Cl ...

Having trouble loading the Google API using getScript. Is displaying a ReferenceError message: "Variable google not found."

I am attempting to dynamically load the Google API using the getScript() method for implementing a "Place Autocomplete Address Form". For more information, you can visit this link: https://developers.google.com/maps/documentation/javascript/examples/places ...

AngularJS: Using controller services to handle REST API calls

Lately, I've been hesitant about reaching out here for help because there are so many resources available, but I'm feeling lost. I'm attempting to create a small Angular app, but I'm struggling to move beyond the basics. My goal is to ...

Struggling to retrieve JSON data within the code

Recently, I've been receiving a JSON data from Microsoft cognitive services but unfortunately, I'm encountering difficulties incorporating it into my code. Is there something that I might be doing incorrectly? I attempted different approaches su ...

Eliminate specific elements from an array while retaining others

Here is a simple page setup: The page consists of an input field at the top, followed by a list (<ul>), and a button for saving changes. The <ul> is connected to an array called items. When the user clicks on "Save Changes", it triggers the fu ...

What does the single-threaded nature of JavaScript signify in terms of its intricacies and ramifications?

As someone relatively new to Javascript and JQuery, I recently discovered that Javascript operates on a single-threaded model. This has left me wondering about the implications it carries: What should be taken into account when writing JavaScript code? Ar ...

The AJAX Contact Form seems to be malfunctioning

I've encountered a persistent issue with my AJAX Contact Form, and all attempts to resolve it have been unsuccessful. The error message from the jQuery section if(html==0) keeps appearing. If anyone can offer assistance in identifying and fixing this ...

How to retrieve specific items from an array contained within an array of objects using Express.js and MongoDB

Within the users array, there is an array of friends. I am looking to retrieve all friends of a specific user based on their email where the approved field is set to true. In my Node.js application, I have defined a user schema in MongoDB: const UserSchem ...

JavaScript in IE/Edge may not run correctly if it is loaded from the cache

I am facing a peculiar problem with Internet Explorer (IE) and Edge. Upon initially loading a page, everything functions perfectly fine. However, if I navigate away from the page to another page on the same website, JavaScript errors start showing up on th ...

The asyncData function in Nuxt is throwing a surprise setTimeout (nuxt/no-timing-in-fetch-data)

Having trouble running a code on my pages/posts/index.vue page where I keep getting an error message 'Unexpected setTimeout in asyncData'. Can anyone provide assistance in understanding this error and suggest if any additional plugins are needed? ...

Surprising non-synchronous operation within the computed property "vue/no-async-in-computed-properties" in Vue3

I am currently working on a Vue3 project and encountering an error when running it. Below is the complete code snippet that I am using. Can anyone assist me in resolving this issue? Thank you in advance. <script> import axios from 'axios'; ...