Understanding the intricacies of Angular's $scope and $watch function can

At the start of my Angular 1.0 journey, I'm gradually getting the hang of it, but some aspects still have me puzzled.

Recently, while working with $watch, I encountered a perplexing issue. Here's the snippet in question:

$scope.$watch('cookies', function() {
    if ($cookies.getAll().redditSession) {
        $scope.$emit('cookiesChanged')
        // $scope.userWelcome = cookieService.decodeCookie($cookies.get('redditSession'))
    }
})

$scope.$on('cookiesChanged', function() {
    $scope.userWelcome = cookieService.decodeCookie($cookies.get('redditSession'))
})

This segment of code functions as intended. When my cookies change, I emit an event that triggers an event listener to update the value of $scope.userWelcome with data from the cookie. This change is reflected when navigating to a different route within my application.

Nevertheless, I find myself questioning why an event emitter was necessary in this scenario. The line I commented out was my initial approach, but it failed to update $scope.userWelcome even after changing routes. Only by reloading the page could I see that I was logged in.

What's the underlying reason behind this behavior?

Answer №1

Maybe consider observing the cookie's behavior:

$watchCookie(
    function () {
        return $cookieManager.fetch('redditSession');
    },
    function (newData) {
        if (newData) { 
            $scope.userGreeting = cookieDoctor.analyzeCookie(newData); 
        };
    }
);

Answer №2

The error you're making is attempting to retrieve the new value using the standard method. To actually obtain the new value, you need to add it as a parameter of the function. Here's how:

$scope.$watch('cookies', function(newValue, oldValue) {
  if (newValue.getAll().redditSession) {
    $scope.userWelcome = cookieService.decodeCookie(newValue.get('redditSession'))
  }
  // Give this a shot too
  console.log(oldvalue === $cookies);
});

Cheers!

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

Access social media login functionality from the client side using AngularJS

I am currently implementing social login in Angular using satellizer. However, I came across a section in the documentation that mentions the need for server-side code as well. The specific lines are provided below: "Additionally, authorization (obtaining ...

Vue.js is able to update various models based on selection from a form dropdown

I have a dynamic select list in my app built with vue.js. I am trying to update a "details" box on the page with information fetched through an ajax request. You can view the code here: https://jsfiddle.net/pznej8dz/1/ I am puzzled as to why the sf_detail ...

Updating a JSON array by including a new key-value pair using Javascript

Below is a json string that needs to be converted into a new Json Array: Raw Data: [ ["yrxqBHmPkNhZ60_eab97ebf-c2a3-40a5-972a-91597ad9a4ca_99371", "SUCCEEDED", "2023-08-31T21:59:31.325000+05:30", "2023-08-31T22:13:42.165000+05:30"], ["yrxqBHmPkNhZ ...

Patiently anticipating the completion of a jQuery animation

I am currently working on some jQuery code that handles toggling containers and buttons. The specific snippet of code I am focused on is the following: var id = $(this).data('id'); if ($('#container').is(':visible')) { $( ...

When using a set of checkboxes, ensure that only one can be selected at any given time

My objective is to have a group of check boxes on a page where only one can be selected at a time. I want the checked box to clear any other selections when clicked. I attempted to implement this functionality in a fiddle, but it does not work as expected. ...

Daterangepicker glitch causing default dates to display as [Invalid date]

I am currently utilizing the Daterangepicker plugin. The start and end dates I retrieve from the backend come in string format, for example (2020-02-22). However, when I try to pass these dates as default values, it doesn't seem to work as expected. ...

Using JavaScript to switch the classes of buttons and elements

Hey there! I received this code from a friend who was trying to modify the switch buttons. I made some changes so that each button can now change the state of two separate elements when pressed. Here's the altered code: function toggleClass(ev){ v ...

JavaScript web developer encounters an issue with MongoDb and Mongoose findOneAndUpdate method, as it unexpectedly returns undefined

I've been attempting to update an item in my mongodb database, but I'm encountering issues as the error keyword is being set to undefined. It's possible that I am making a mistake somewhere. Here's the code for the update function: rou ...

add to array object if it does not already exist

I am currently working with the following model in JavaScript and utilizing AngularJS: $scope.data = { FocusOn: " ", Filters: [], Range: { From: "", To: "" } } Additi ...

When invoking the Angular function to make an HTTP request, it will generate a recurring loop

When trying to call a function in mg-repeat that makes an HTTP request with an ID to find a list of data, I encountered an error message. Here is the function call: <div ng-repeat="ListeReponse in reponsefonction(Listechamps.keyQuestion)" > < ...

Is it possible to have content in an array with a length of 0?

Here is the test code that I am using: console.log('AA',slider); console.log('AB',slider.length); When I check the Chrome console, it shows the following results. AA Array[53] AB 0 I included this test code because even though there ...

I'm having trouble loading gltf files in Three.js GLTFLoader on my computer

Recently, I began exploring the world of three.js, JavaScript, HTML, and CSS as I delve into the process of loading a 3D model. So far, I've had success when retrieving a gltf file from an online source, like this: loader.load('https://threejsfun ...

What is the best way to dynamically update or display unique CSS styles when a service is invoked or provides a response in AngularJS using JavaScript

Seeking to display a unique CSS style on my HTML FORM prior to invoking a service in my code and then reverting back after receiving the response. I have implemented the use of ng-class to dynamically add the class when the boolean activeload1 is set to tr ...

Unable to execute JS script to navigate back to prior page with webdriver

Here is my code snippet: JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("window.history.go(-1);"); The code above isn't working. I've tried casting the webdriver instance but it doesn't work every time. I prefer not ...

Creating Bound HTML inside an AngularJS Grid Cell Template

I recently started using angular js and came across a helpful question on Conditional cell template in ui-grid angularjs. It worked perfectly for me, but now I'm curious about how to display HTML elements like a button tag instead of plain text. Whene ...

javascript verify that the input is a valid JSON object

Seeking assistance with an if statement that checks for a json object: updateStudentData = function(addUpdateData) { var rowDataToSave; if(addUpdateData.data.row) { rowDataToSave = addUpdateData.data.row; } else { rowDataToSav ...

Is there a way to turn off the compilation of Angular expressions in HTML without affecting the functionality of directives?

Is it possible to prevent Angular from evaluating template expressions while still allowing the use of directives? My dilemma is somewhat similar to another query. The issue at hand: Incorporating both legacy server-rendered content and AngularJS content ...

Converting Datepicker selection to a string format in AngularJS

Can anyone help me figure out how to convert a datepicker value into a string that can be passed as a parameter to a get method without causing an error? <div ng-app="getserviceApp" ng-controller="getserviceCtrl"> <button ng-click="Func ...

The functionality of Angular template routing is non-functional

When trying to view my angular project, I want to load a template HTML in my main index.html but all I get is an empty screen. <!DOCTYPE html> <html lang="nl" ng-app="store"> <head> <meta charset="UTF-8> <title>NMDAD- ...

Changing the custom route in React Router to utilize a render prop instead of the component prop

I'm currently working on a React app that incorporates React Router. I've been encountering a bug in my code stemming from my custom ProtectedRoute component: const ProtectedRoute = ({ component, ...args }) => ( <Route component={with ...