AngularJS 1.5: Observing scope changes with $watch in the link function fails to register updates when the model is modified

Greetings everyone!

I'm currently working on a web application using typescript and angular 1.5;

One of the components I've built is a directive that aims to monitor whether a user is logged in or not, and accordingly show or hide certain elements.

Below is the snippet of the link function code:

interface ShowAuthedScope extends ng.IScope{
  User: UserService,
  _$log: ng.ILogService
}

function ShowAuthedDirective(User:UserService, $log:ng.ILogService) {
  'ngInject';

  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      scope.User = User;
      scope._$log = $log;
      scope.$watch('User.current', function (val) {
        scope._$log.log('updated!:', val);
      })
    }
  }
}

In this scenario, the model revolves around the current user's status, which can change based on their login state.

And here is an excerpt of the UserService code:

interface UserInterface {
  current:GoogleUser;
  signIn(options?:SignInOptions):Promise<any>;
  signOut():Promise<void>;
}

class UserService implements UserInterface {
  public current:GoogleUser;
  private _GoogleAuth:GoogleAuthService;
  private _AppConstants;

  constructor(GoogleAuth:GoogleAuthService, AppConstants) {
    'ngInject';
    this._GoogleAuth = GoogleAuth;
    this._AppConstants = AppConstants;
    this.current = null;
  }

  public signIn(options?:SignInOptions) {
    let promise:Promise<any>;
    let _options:SignInOptions = options || {};
    _options.app_package_name = this._AppConstants.appPackageName;
    if (this.current) {
      promise = this.current.signIn(_options);
    } else {
      promise = this._GoogleAuth.signIn(_options);
    }
    promise = promise.then((googleUser:GoogleUser) => this.current = googleUser);
    return promise;
  }


  public signOut() {
    this.current = null;
    return this._GoogleAuth.signOut();
  }

}

The $watch function trigger only occurs once upon initialization;

It's worth noting that I have already attempted passing true as the third parameter in the $watch function

Any assistance will be greatly appreciated! Thank you!

Answer №1

Executing signIn and signOut commands directly from the console bypasses the normal "Digest Cycle" process in Angular. This cycle is responsible for running $watch statements, but it requires a trigger to initiate.

Typically, directives like ng-click automatically trigger the digest cycle when handling events, allowing changes to be detected in variables.

Therefore, if you intend to perform actions solely through the Console, you must manually trigger the digest cycle:

angular.element(document).injector().get('$rootScope').$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

Tips for automatically filling out a div class form:

I currently have an Autoresponder email form featured on my webpage. Here is a snippet of the code for the section where customers enter their email: <div id = "af-form-45" class = "af-form" > <div id = "af-body-45" class = "af-body af-standa ...

How can I retrieve the value of a nested reactive form in Angular?

I'm working with a nested form setup that looks like this: profileForm = new FormGroup({ firstName: new FormControl(''), lastName: new FormControl(''), address: new FormGroup({ street: new FormControl(''), ...

I need assistance with retrieving the value in a password field using JavaScript. I've been stuck on this issue all morning and would greatly appreciate any

Currently utilizing document.getElementById("password").value for retrieving the input value of the password field. Seeking assistance! Additionally, the form contains an action="authenticate_signup.php" Encountering an issue where the password field va ...

Issues with importing files have been reported on Node.js version 11.8.0

I'm currently working on a program that utilizes a large object filled with dictionary words. I've decided to import this object from a separate file due to its size, but I encountered an error stating that Node.js doesn't recognize the obje ...

NgrxStore - An initial item has been added twice to the array

Currently experimenting with ngrx store and manipulating elements within an array, such as deleting, fetching, and editing, works smoothly. However, a challenge arises when inserting an object into the array for the first time, duplicating the entry unless ...

Vue: utilizing shared methods in a JavaScript file

Currently, I am building a multipage website using Vue and I find myself needing the same methods for different views quite often. I came across a suggestion to use a shared .js file to achieve this. It works perfectly when my "test method" downloadModel i ...

Hot Towel Angular with Visual Studio 2015

I recently installed Visual Studio 2015 RC1 and attempted to install the Hot Towel Angular Package. However, upon installation, I encountered the following messages in the output window: Successfully installed 'HotTowel.Angular.2.3.3' to Value ...

The node server is experiencing difficulties connecting to the mysql database, resulting in a timed out connection error at Connection._handleConnectTimeout

Having trouble establishing a connection with the mysql database. Every time I attempt to start the node server, it keeps throwing a database connection error. The specific error message is as follows: connect ETIMEDOUT at Connection._handleConnectTimeou ...

Step by step guide on rotating a plane with texture by 90 degrees

I've been working on developing an fps game, but I'm encountering an issue where the floor disappears from the scene when I try to rotate it close to 90 degrees. Here's the code snippet responsible for creating the plane. var colorMap = new ...

how to handle form submission using JavaScript's return method

As a developer, I have created a single page that fetches data from a registration page. On this page, each data row has an "add" and "unfriend" button, with the latter initially disabled. When a user clicks the "add" button, a prompt box appears asking ...

Creating first-person shooter game controls using Three.js in JavaScript

I am currently in the process of creating a small 3D FPS Game using Three.js, but I am in need of assistance with the controls. To better illustrate what I am aiming for, please watch this video to see the desired controls in action (only the controls, no ...

Tips for activating Vue.js production mode with webpack 2.7

I have encountered performance issues with Vue.js in my existing code base. Additionally, I noticed a notice in the browser console: https://i.sstatic.net/KY1B3.png So, I believe that one simple solution could be to switch Vue into production mode. Foll ...

In TypeScript, develop a specialized Unwrap<T> utility type

After successfully creating a helper type to unwrap the inner type of an Observable<T>, I began wondering how to make this type completely generic. I wanted it to apply to any type, not just Observable, essentially creating Unwrap<T>. Here is ...

Using Typescript to import an npm package that lacks a definition file

I am facing an issue with an npm package (@salesforce/canvas-js-sdk) as it doesn't come with a Typescript definition file. Since I am using React, I have been using the "import from" syntax to bring in dependencies. Visual Studio is not happy about th ...

Utilizing Generic Types in React TypeScript Functional Components

I'm currently developing a TypeScript React component that includes generic type props, so I define the React component as: export interface MyCompProps<T> { items: T[]; labelFunction: (T) => string; iconFunction: (T) => JSX.Element; ...

Tips for utilizing a MySQL function within Sequelize using TypeScript

I need to utilize the Year function on the date column in order to compare years. When dealing with the data in raw format, you can create a query like this: Select * from Table where YEAR(date) = 2020 Is there a way to translate this query into sequeli ...

Can a ternary operator be used within an index type query when extending a partial type?

Can anyone provide a detailed explanation of the process unfolding in this snippet? I'm having trouble grasping how this code leads to a type declaration. type ModalErrors = Partial< { [key in keyof InputGroup]: InputGroup[key] extends Speci ...

Is it possible for an AJAX request to return both HTML data and execute callback functions simultaneously?

Is it possible to update the content of an HTML div and call a JavaScript function with specific parameters obtained through AJAX after the completion of the AJAX request, all within a single AJAX call? ...

Generate SVG components without displaying them

Is there a way to generate a custom SVG graphic through a function without the need to attach it to any element? Can I simply create an empty selection and return that instead? Here is my current implementation: function makeGraphic(svgParent) { retur ...

Leveraging React's state to enable temporary invalid numeric input handling

My current approach may be flawed, but I aim to have a parent component and a child component, where the child contains an input field for users to enter numbers. The callback function of the parent component will only be triggered for valid numbers, as ve ...