`Why isn't Angular updating when watching window.pageYOffset?`

Within my controller, I have the following code:

$scope.woffset = window.pageYOffset;

 $scope.$watch("woffset", function (newValue, oldValue) {
    console.log("hello");
    console.log(window.pageYOffset);
 }, true);
});

My expectation is to receive console logs of "hello" as the pageYOffset changes while scrolling. Unfortunately, it doesn't seem to be working as intended. However, when manually checking window.pageYOffset in the console as I scroll down, I can see that the value is indeed changing. Any suggestions on what might be causing this issue?

I've attempted various iterations with watch methods, including using functions instead of strings and experimenting with different parameters like "true", but so far, nothing has resolved the problem.

(I am aware there is an alternative solution involving onscroll, but I'm interested in understanding why this particular approach is not functioning correctly) Thank you for your assistance!

Edit: Even trying the following modification didn't yield the desired outcome:

$scope.test = function () { 
    return window.pageYOffset;
}

$scope.$watch("test", function (newValue, oldValue) {
console.log("hello");
console.log(window.pageYOffset);
}, true);

Answer №1

The issue arises from the fact that $scope.woffset remains unchanged, much like in the example below:

var i = 5;
var j = i;

i = 7;
// It's puzzling why j doesn't become 7

To tackle this problem, there are two approaches you can take - the straightforward way or the more effective method.

Firstly:

window.onscroll = function () {
    console.log("hello");
    console.log(window.pageYOffset);
    // update any $scope variables here
    $scope.$digest();
};

However, using this solution means it will run excessively each time you scroll. A more efficient approach would involve implementing the above solution along with some form of "debouncing" - for more information on this, refer to this Stack Overflow query: Can I debounce or throttle a watched <input> in AngularJS using _lodash?

A concern with this method is that it will continue watching scrolling even after the controller has been removed. To address this issue, follow these additional steps:

$scope.$on('$destroy', function() {
    window.onscroll = null;
});

Answer №2

A helpful tip is to ensure that your window's pageYOffset value is actively changing. Try scrolling the window and then running a window.pageYOffset command in the console to confirm its movement. It's possible that you may be inadvertently scrolling within a nested container instead of the main window, leading to no apparent change.

Answer №3

let scrollResizeEvent = angular.element($window).on("scroll resize", function (e) {
    console.log($window.pageYOffset)
});

scope.$on('$destroy', function () {
    scrollResizeEvent.unbind("scroll resize");
});

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

Issue: { error: 'Unrecognized interaction', error code: 10062} in discord.js version 14

Every command runs perfectly fine except for /rank, which triggers the "Unknown interaction" error. This only happens when there are no issues with error handling, such as providing a valid user id and rank id. When there are problems, it works fine. I pr ...

Tips for successfully accessing a variable in an Angular Pipe

When displaying output, I need to show a specific number of decimal digits based on the length returned by a stored procedure. The length of these decimal digits can vary, and I only need to focus on the decimal part, not the integer part. To achieve this, ...

What steps do I need to take to deploy my React app onto a server?

I recently completed creating my first website with React and now I want to upload it to my server (HostGator). Can anyone guide me on how to do that? Thank you. ...

Ways to unveil a concealed div element using JavaScript

If javascript is disabled, I want to hide a div. If javascript is enabled, however, I don't want to rely on using the <noscript> tag due to issues in Chrome and Opera. Instead, my approach is as follows: <div id="box" style="display:none"> ...

Encountering a Parsing error while utilizing redux: Unexpected token present

Trying to implement Redux for managing the searchField state on the website. After creating action.js, reducer.js, constant.js, and redux.connect() function, An error occurred: Parsing error: Unexpected token 62 | return <div className=&apo ...

Tips for choosing a single checkbox from a set of multiple checkboxes in React.js

I iterated through a list of objects to generate table rows, each containing an input tag with the type set as checkbox. const [ isChecked, setIsChecked ] = useState(false); const handleChange = (e) => { setIsChecked(e.target.checked) ...

Is there an optimal method for executing shell commands quickly in Node.js?

How can I efficiently run a large number of shell commands sequentially, for example 50 or 60 commands one after the other? For instance: const arr = ['/hello', '/temp', '/temp2', '/temp3', '/temp5', ...... ...

The bodyparser in Express seems to be malfunctioning

When configuring my body parser, I implement the following code: const express = require('express') const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extend ...

Using Jquery to Retrieve the Attribute Value from an HTML Element

I am currently developing an interactive online quiz application that is organized by chapters, with each chapter having its own quiz. Users can navigate through the chapters via a menu and start quizzes by clicking on a button after loading the chapter co ...

an all-encompassing loading animation designed specifically for updates to location.href

We have a situation where a customer's website is displaying extremely slowly within an iFrame, taking about 7 seconds to load. All we can do is provide the customer with a JavaScript file for inclusion on their site, as they are not willing to make a ...

Error in Material UI when using the select component

CustomComponent.js:98 UI Error: The value undefined provided for the selection is out of range. Please make sure to select a value that matches one of the available options or ''. The available options are: `All`, `Software Development`, `Qualit ...

What is the best way to determine if an application has been installed on an Android device while browsing a website?

Let's set the scene: I've got a website that needs to use JavaScript to determine whether my app is already installed on the android device it's currently being used on. If the app is installed, the page will display a link (with a custom ...

Encountering Issues with NextJS Dynamic SSR: Mobile Devices stuck on loading screen

Issue: The dynamic import feature of Next JS is encountering loading issues specifically on mobile browsers such as Google Chrome and Safari on IOS. Strangely, the functionality works smoothly on desktop browsers like Google Chrome and Mozilla. The projec ...

Is it possible to send information via the URL while using jQuery Mobile?

My mobile application utilizes an in-app browser to send information, such as deviceID, to my server via a URL. For instance, the browser opens a web-page (jquery Mobile): www.myserver.com/doWork.html#deviceID Within the doWork.html file on the server si ...

Investigating Jquery Flip Card Issues

Looking to create a set of flip cards using HTML, CSS, and jQuery. Currently facing an issue where only the first card is flipping when clicked. Any suggestions on how to modify the jQuery code to make it work for all cards would be highly appreciated. C ...

Having difficulty retrieving data in mongodb using category id

Currently, I am attempting to sort and filter my pets based on categories. The pets are modeled as follows: const Pet = mongoose.model( 'Pet', new Schema({ name: { type: String, required: true, } ...

Tips for positioning buttons in a row below dynamic text using Bootstrap 3

Is there a way to align buttons under a variable piece of text in Bootstrap 3? Currently, when the code example is viewed in full screen, the three buttons do not align horizontally. Current Behavior: https://i.sstatic.net/lEQ7o.png My goal is to have t ...

Exploring the creation of dynamic DOM elements within Angular

I'm having trouble figuring out how to create a DOM element in Angular and pass it to jsPlumb, which I'm using to draw charts. When creating connections between nodes using jsPlumb, I also need to create an overlay on these connections. The offi ...

Rotating a camera in ThreeJS for a quick orbit

I am using an orbital camera that orbits around a globe with markers for users to interact with. When a user clicks on a marker, the camera moves to that specific point. To animate this movement, I am utilizing TweenMax as shown below: TweenMax.to(curre ...

Navigating through radio button groups in AngularJS

I am currently developing a survey application using AngularJS. My goal is to display tasks one at a time, each containing one or more questions with radio button answers. I am looking to store the question and answer pairs in a new array. While I have ma ...