Is it possible for AngularJS to activate $watch on a specific URL whenever new data is updated on a different URL

I'm curious if I can use the $watch function to detect changes in the database that are not initiated by the user's actions on their current page.

For instance, within the controller:

.MesgCtrl(...)
$scope.data = {'name': 'Tim', 'visits': 0};

$scope.$watch('data', function(newValue, oldValue) {
  console.log("$watch triggered");
  });

And in the template.html:

<ul ng-repeat="d in data">
  <li>{{d}}</li>
</ul>

A different REST endpoint URL receives POST requests for visits and updates them in the database when they occur. I want the visit counts to also update in template.html without any action from the user, but so far I've only been successful in using $watch when calling $resource.save() to update visits from the same AngularJS Controller URL, not a different one.

Answer №1

For effective two-way communication, such as receiving client updates when another user visits a page, consider utilizing a library like socket.io http://socket.io/ which caters to all connected sockets).

You may also incorporate a timer to periodically request updates from the server every 30 seconds and retrieve the latest visit count (utilize $interval for this purpose).

If you prefer to request the update only once after a specific time interval has passed, use $timeout.

Answer №2

$interval successfully managed to schedule updates and propagate modifications to the Web Browser Client. Below is the snippet of code utilized for this functionality:

conciergeControllers.controller('MessageCtrl',
    function MessageCtrl($scope, $stateParams, $interval, Message, GuestMessages) {
        $scope.messages = {};

        $scope.requestGuest = function(GuestMessages, $stateParams, $scope) {
            GuestMessages.get({
                id: $stateParams.guestId
            }, function(response) {
                $scope.guest = response;
                $scope.to = response.phone_number;
                $scope.messages = response.messages;

                // test
                console.log('Guest:', $scope.guest);
            });
        }
        // load initial context without a delay
        $scope.requestGuest(GuestMessages, $stateParams, $scope);

        $interval(function(){ $scope.requestGuest(GuestMessages, $stateParams, $scope); }, 5000);
    }
);

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

What is the process for sending Raw Commands to a Receipt Printer using Node.JS?

My Current Project I am currently working on integrating a receipt printer that supports ESC/P raw printing into an app for remote printing of receipts. The Approach I Am Taking To achieve this, I am utilizing the PrintNodes API to send data from my app ...

Encountering issues when trying to build a Vue application with Vue CLI and running npm start

I am attempting to develop an application using the **Vue CLI** command - npm create vue@latest Following the npm install, I am endeavoring to launch my app with **npm run dev** but encountering the error below. Any assistance would be greatly appreciated ...

Looking to create circular text using HTML, CSS, or JavaScript?

https://i.sstatic.net/pnu0R.png Is there a way to generate curved text in HTML5, CSS3, or JavaScript similar to the image linked above? I've experimented with transform: rotate(45deg); but that just rotates the text without curving it. Additionally, ...

Is it possible to rerun the $onInit function within a different method?

I am facing an issue where I have two different grids both calling the same controller and grid component. My goal is to show/hide a checkbox in one grid based on a certain condition. However, since the gridOptions are loaded during the OnInit method initi ...

Using AngularDart: Maximizing Efficiency with Dual ng-repeat Expressions in a Single Tag

I am looking to create a grouped table that resembles the following structure: Customer Site ------------------------------ Customer 1 Site 1.1 Site 1.2 Site 1.3 Customer ...

Guide to extracting additional data from a JSON array upon selection of a value within an option tag using jQuery

Seeking assistance to enhance the display of museum information when a museum name is selected from an option dropdown box. The data is extracted from a json array. Although I managed to populate the option box with the museum names, I am encountering di ...

Using HTTP POST to subscribe and implementing a try-catch block

When using Angular2's http.post, I encountered an issue where the headers were not sent to the CORS server. To address this, I attempted to create a loop that would retry the request until it succeeds. However, this resulted in an endless loop. How ca ...

Displaying a notification for a multi-selection using JavaScript

I need help with a piece of Html code I have. It's a list of countries, and what I want is to show an alert when one or more countries are selected to display which ones were chosen. I'm working with JavaScript only and don't want to use Jqu ...

The functionality of ng-switch appears to be malfunctioning

Take a look at this code snippet: <script src="angular.min.js"></script> <script src="jquery-1.6.4.js"></script> <script type="text/javascript"> var app = angular.module('myApp', []); app.controller("myContr ...

Calculate the average value of the properties of a jQuery object

Consider the object below: rating { atmosphere: 85 cleanliness: 91 facilities: 91 staff: 85 security: 94 location: 78 valueForMoney: 85 } I'm looking to calculate the average of all these property values. Can y ...

Real-time preview of a text field in JavaScript

I'm attempting to create a similar piece of code like the one at the bottom of this page for leaving comments. I have the basic code, but the result doesn't display new lines (or HTML, although that's not essential). I have the function belo ...

Capturing events beyond the scope of Reactjs using vanilla JavaScript

Is there a way to intercept the click event of an element triggered by a React component and replace its functionality with native Javascript? window.addEventListener('load', function() { var el = document.getElementById('button'); ...

Tips on displaying a loading animation before the element appears in an Angular application

When fetching data using an Angular service, it takes approximately 2-3 seconds for the information to appear. Consequently, the corresponding HTML elements also take time to load. Is there a method to display a loading animation specifically for those e ...

Angular.js' Element.prop('scrollHeight') consistently gives identical values for various list items

I have been attempting to determine the heights and widths of the items in my list. Despite exploring various methods for obtaining the height and width of an item, none of them seemed to provide the scrollHeight directly from the element. Upon inspecting ...

Utilizing Express-Partials in conjunction with a single layout to incorporate multiple partials

Recently, as I migrated to Node.js and ExpressJS 3.0, I noticed that partials were no longer supported. However, I stumbled upon express-partials which provided a similar feature. Upon exploring the example on their GitHub page, I came across this snippet ...

Controlling worldwide modules using Node Version Manager

Currently, I am utilizing nvm as a tool to manage node.js / io.js versions, encountering difficulties with global modules every time I update node. Recently, I attempted to install npm i express-generator -g. I noticed an older version in /usr/local/bin a ...

When transferring data from Django rest framework to a JavaScript array, there may be issues with missing

Struggling to retrieve data from my API endpoint using AJAX. During the iteration of the JSON object to populate my JavaScript array, I seem to be overlooking some values. Here's a breakdown: API data: HTTP 200 OK Allow: GET, HEAD, OPTIONS Conte ...

Automated scrolling within a div when an li element overflows

Looking to implement automatic scrolling in a div. I have a list of elements within a fixed height div, and now I want the div to scroll automatically when I press the down key after highlighting the 3rd li element (i.e Compt0005). Can anyone help me solve ...

Encountering an error when trying to destructure a property of null

The concept of destructuring is fascinating, but I have been facing some challenges when trying to destructure nested objects. Consider the following code snippet: const { credit: { amount }, } = userProfile This can be risky because if the &ap ...

The function getattribute() on the edge is malfunctioning and returning a null value

Has anyone encountered issues with the getAttribute() function while creating an extension for Edge? I am currently facing a problem where it is not returning the attributes of the element that I am searching for. This is what my code looks like on Edge a ...