Angular $watch fails to fire upon modification of $scope variable

At the start of my application, I need to execute a routine using user data that is fetched during initialization.

In the controller for the homepage, I check if there is a token stored (indicating a logged-in user) and then proceed to run the routine if $scope.currentUser already exists. If not, I set up a watch on it to trigger once the AJAX call returns the necessary data.

However, I am encountering an issue where the $watch callback never gets triggered after its initial setup.

Below is the code for the Feed Controller:

if (sessionStorage.getItem('token'))
{
    if ($scope.currentUser) {getItems()}
    else {$scope.$watch('currentUser', popFeed()) }
}

function delayForUser()
{
    if ($scope.currentUser) {popFeed()}
}

And here is the code for the Application Controller:

if (sessionStorage.getItem('token') && sessionStorage != 'null')
{
    UserSvc.getUser()
    .then(function (response) 
    {
        $scope.currentUser = response.data
    })

Answer №1

If both controllers have access to the currentUser variable, then you should pass a function as an argument to the $watch method instead of directly executing it:

$scope.$watch('currentUser', function(updatedValue) {
    updateFeed();
});

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 on saving data in an AngularJS factory after receiving a response from another factory

IFactory.query( function (response) { $scope.type_content = response; $scope.showMenu = true; }, function (response) { $scope.message = "Error: " + response.status + " " + response.statusText; } ); $scope.saving = ...

Unable to locate module - relative file path

I'm currently running a test with the following code and encountering an error message: Failed: cannot find module '../page/home_page.js The main page consists of: describe("login to website",function(){ var employeeId; var employee ...

Insert a CSS Class into an HTML div element with JQuery

I'm faced with a bit of a challenge. Here's the scenario: <div class="portItem"></div> <div class="portItem"></div> <div class="portItem"></div> <div class="p ...

Learn how to retrieve data from a dynamically populated drop-down menu when a button is clicked using PHP

I am having trouble retrieving the value from a dropdown menu. The dropdown is populated dynamically from an SQL Server database. Dropdown 1 displays product names and is filled dynamically. Dropdown 2 displays environment names and is filled using HTML. ...

Is there a way to update and reload the latest data in ApexCharts?

Can anyone assist me in resolving my issue? I have an ApexCharts that displays data, and I need it to refresh whenever the user desires. The data should also be updated with the latest information. However, I am unsure how to reload the data in ApexCharts. ...

Mapping dynamic objects inside a repeat loop in AngularJS ui-select

Here is my ui-select directive code that is working perfectly fine. Within a repeat loop, I need to dynamically set the property of the CODE object (which is ID) to something like code[fwValueProperty]. Since it is not using ng-repeat, I cannot use it in ...

What is the best method for retrieving a JSON string that contains commas?

I have a JSON data with coordinates: "geometry":{"type":"Point","coordinates":[95.9174,3.8394,59]},"id":"us10002b0v" I am looking to extract each value in the coordinates array that is comma separated. In PHP, I would use extract(",",$geometry[coordinat ...

What causes the ng-bind directive to fail when used with arrays?

I'm looking to bind an array to an element so that any changes made to the array will update the corresponding HTML. However, I'm encountering some issues with this implementation. HTML <body ng-controller="Game as game"> <div> ...

In the `componentDidUpdate()` method, the function `this.props` is not

I've encountered a peculiar issue that I just can't seem to figure out. It's possible that I missed something simple, but I'm stuck trying to solve this bug. Here's what's happening: In the child component, a counter is being ...

When I try to use the mongoose find() function, I am receiving a Promise status of <Pending>

I recently developed a function to retrieve the list of all products stored in MongoDB using mongoose. However, when trying to log this information, I am unexpectedly getting a Promise instead. Below is the relevant code snippet: router.get('/', ...

Having trouble with your Ajax call to an express route?

Trying to initiate an ajax call from a JavaScript file to an express route within a Node.js application, while keeping in mind that the JavaScript file is also part of the same Node.js application. Encountering an issue where the data passed to the route ...

function complete, ajax request finished

When working with Ajax to get data, I encountered a situation where I needed to return the value of `username` from within an if statement that is inside a loop and a function. How can I achieve this? Your help would be appreciated. $.ajax({ ...

What is the best way to assign a unique number to every div id that is generated?

I am currently using a django for loop to retrieve data from a query set. As the information is displayed, I would like to have each item wrapped in a div tag with a unique id that increments by 1 for every instance. Is there a way to achieve this directly ...

Import the information into a td tag's data-label property

I have implemented a responsive table design that collapses for smaller screens and displays the table header before each cell. body { font-family: "Open Sans", sans-serif; line-height: 1.25; } table { border: 1px solid #ccc; border-collapse: co ...

cutting tags with priority levels

I'm facing an issue where the vertical label "PINK" is centered perfectly in a section, but when I scroll down to the next section, it gets covered by a section with a higher z-index. div.back1 { background-color: #FF00FF; position: relativ ...

Is a single script tag sufficient for each AngularJS Controller?

Recently started using angularjs and I'm really enjoying it. My goal is to make my app as modular as possible. I have a question: Should each angularjs controller (service, etc) have its own script tag? Is there a way to dynamically load angular contr ...

Ensure that every `then()` function either returns a value or throws an error

I've been encountering an issue while attempting to send push notifications through cloud functions for a group chat application. The error message that keeps popping up in my terminal says: Each then() should return a value or throw What could be ca ...

Tips for retrieving specific information from Wikipedia using AJAX

Is there a way to retrieve the information consistently displayed in the right box during searches using AJAX? I've tried using the Wikipedia API, but haven't been able to find the specific information I need. https://i.sstatic.net/wqJEc.png ...

Changing the stylesheet on a single-page application

Our angular-built single page app features a drag-and-drop interface for code snippets, each with its own unique styles separate from the main Bootstrap-themed admin panel. However, due to the differences in styling, navigating to the drag-and-drop sectio ...

Searching for a document in mongoDB using the `findOne` method

I attempted to use a query to find one document in MongoDB and then I tried to log it, but the result was null. const pc = await ProductCategories.findOne({categoriesName : kategor)}) console.log(pc) I expected to retrieve 1 collection from this process { ...