Exploring the changes in rootscope with AngularJS

I am attempting to connect to $rootscope in order to establish presence on a different server when the user logs in. Below is the code for my module.

angular.module('presence', 
  [
  ]
)

.run(function ($rootScope) {
  $rootScope.$watch($rootScope.currentUser, function () {
    console.log('change currentUser')
    console.log($rootScope.currentUser)
    presence.setGlobal({
      u: $rootScope.currentUser,
      s: 'on'
    })
  })
})

There is no controller involved because this is solely related to the global presence of the user and does not interact with the DOM.

Unfortunately, there seems to be an issue with the code as the watch only triggers once and does not respond on subsequent changes. Your assistance will be greatly appreciated. Thank you.

Edit: The login code is as follows:

  $scope.login = function() {
    $http.post('http://localhost:3000/login', $scope.user).success(function(res, status) {
      if (res && res._id) {
        $rootScope.currentUser = res
      }
    }).error(function(res, status) {
      $scope.error = res.err
    });
  };

This code successfully updates in the DOM. For instance, it displays the username in the HTML like this:

a.user(ui-if="currentUser", ng-href="/user/{{currentUser._id}}") {{currentUser.username}}

Answer №1

Remember, the correct syntax is $rootScope.$watch('currentUser') rather than

$rootScope.$watch($rootScope.currentUser)

Answer №2

In order to observe any changes in $rootScope.currentUser, you must make modifications to it. The code provided demonstrates how to do this.

Furthermore, any alterations to $rootScope.currentUser should occur within the angularJS loop (refer to http://docs.angularjs.org/guide/concepts). If changes are made externally, you can invoke $digest (http://docs.angularjs.org/api/ng.$rootScope.Scope#$digest).

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

Uploading documents using AngularJS and Express.js

I'm currently working on a project that involves uploading files using AngularJS and Node.js (with Express.js). To facilitate this process, I am utilizing danialfarid/angular-file-upload. Within my view (built with jade), the code snippet below showca ...

Creating a Login Form with Node.js and MongoDB

Currently, I am working on a node.js application that is connected to a remote mongoDB server. Inside the database are specific custom codes that have been created and shared with selected users. The main objective is to restrict access to the rest of the ...

Display a "Loading" image in the gallery before anything else loads

Can a animated loading gif be implemented to load before the gallery images, or would it serve no purpose? The image will be loaded as a background using CSS. <link rel="stylesheet" href="loading.gif" /> Appreciate your help! ...

"Extracting key names from an array of objects in AngularFire: A step-by-step guide

I'm in need of some assistance in extracting the unique object name from contents ($Id). Although I can successfully loop over $scope.data in my template using ng-repeat, I am struggling to retrieve the name of that array. This information is crucial ...

How can I use the import statement to incorporate the 'posts.routes.js' file into my app using app?

Searching high and low for answers but coming up empty. When setting up an express app and including a file of routes, you typically encounter guidance on using the following statement: require('./app/routes/posts.routes.js')(app) As per nodejs. ...

Utilizing a Meteor Method within a Promise Handler [Halting without Throwing an Error]

I've been working on integrating the Gumroad-API NPM package into my Meteor app, but I've run into some server-side issues. Specifically, when attempting to make a Meteor method call or insert data into a collection within a Promise callback. Be ...

Postman Guide: Mastering the Evaluation of JSON Arrays

One of the features in Postman allows users to save a specific field from the response body as a variable and then utilize that variable in a subsequent call. For instance, after my initial call to the web service, the response body contains: [ { "id" ...

Issue with debugging capabilities in Javascript on VSCode has been detected

UPDATE: I'm seeking guidance on configuring VSCode for debugging Javascript. While I'm familiar with JavaScript functioning in a browser, I find it tedious to rely solely on console.log(). I am looking to debug and step through my code effectivel ...

Enhancing OpenSeadragon images with custom overlays and managing error messages

Currently, I am experimenting with the Basic Single-Row Tile Source Collection example using the same configurations and tile sources outlined in the example. However, I am encountering difficulties in adding overlays to the first and second images as int ...

Building Individual Elements in Angular 2

My task involves creating two distinct components in Angular 2, the Users component and the Clients component. These components are not nested and do not have any relationship. To call these components separately, I typically use main.ts as the main entry ...

Ember Gain a comprehensive understanding of the flow of execution between route and controller

Below is a snippet of my "box" route/controller: export default Ember.Controller.extend({ initialized: false, type: 'P', status: 'done', layouts: null, toggleFltr: null, gridVals: Ember.computed.alias('mode ...

Enhance text search functionality using AngularJS

Just starting to learn angularjs. Below is the code I've written: $scope.styles = [{"name":"walking"},{"name":"Food"},{"name":"culture"}] I have created a checkbox list <div ng-repeat="style in styles"> <input type="checkbox"> {{ ...

Tips for dynamically setting an HTML ID tag with AngularJS

When setting the html src tag like <img ng-src="{{phone.imageUrl}}">, I know how to do it. But how can I set an id tag like <span id="sourceId::{{post.id}}" class="count"></span> ? I attempted to use <span id="{{ 'sourceId::' ...

Modify the layout of a JSON data structure

Here is an example of an array: let array = [ {1: { "date": "2014-04-23 00:00:00", "volumetrie": "22458" }}, {2: { "date": "2014-05-02 00:00:00", "volumetrie": "30585" }}, {3: { "date" ...

Creating a structure for data in Ruby on Rails to facilitate AJAX calls to controller actions

I am in need of a button on my website that can send data to the create action of a controller named "pagetimes". The functionality seems to be partially working, but it is not sending all the specified data. This issue may be due to my inability to struct ...

Creating an object in AngularJS by merging data from three separate API calls

I am looking to develop a Jenkins dashboard using AngularJS. I am considering combining data from three different API calls to create an object that can be used in the HTML file with ng-repeat, but I'm not sure if this is the best approach. The desir ...

Show a button using CSS when the cursor is hovering

Expressing my gratitude to everyone! I need assistance with implementing a function in reactJS where the <button /> remains hidden during page loading and reveals itself when hovered over. Despite trying various methods, I have been unable to resolve ...

Smoothly scroll to the bottom of a dynamically updated div using native JavaScript

I am in the process of developing a chat application and my goal is to achieve a smooth scrolling animation that automatically moves the page down to the bottom of the div when dynamic messages are loaded. <ul id="messages"> <li ...

Loop Swig with Node.js and Express!

I'm attempting to create a loop in order to access array objects using swig. The goal is to make a loop that checks the object's length. I am able to access the objects by {{styles[0].style}}, where [] represents an array. So, essentially what I ...

What is the best way to pass default event argument alongside another argument in React?

This snippet demonstrates the function I wish to call when a certain input type is invoked: _handleOnEnterPress = (e, receiverUserId) => { if (e.keyCode === 13) { // assuming keycode 13 corresponds to 'enter' console.log("pressed ...