Adjusting the height of an element based on changes in screen width or height using Angular

I'm in the process of developing a directive that can detect changes in screen size, either width or height, and adjust the height of my element accordingly.

The main goal is to have my element extend all the way to the bottom of the browser window.

This is the code for my directive:

.directive('strechToBottom', ['$document', '$window', function ($document, $window) {
    return {
        restrict: 'A',
        link: function (scope, element, attributes) {

            var space;

            scope.$watch(function () {
                return $window.innerHeight;
            }, function () {
                space = $window.innerHeight - element[0].offsetTop;
                element.css('min-height', space + "px");
            });

        }
    };
}]);

Initially, everything works fine when the element is first created. However, the issue arises when I resize the screen - the function isn't triggered immediately. It seems like there's a delay before the function kicks in during the cycle, which is confusing to me.

I also attempted to listen for innerWidth changes, but that approach didn't yield any results either.

What could be causing this problem in my code?

Answer №1

When you bind to all scope digests, as seen by passing a function to `$scope.$watch` as the first argument, the function will execute in a non-deterministic manner from your perspective. Essentially, it will only run upon some interaction with the application (though this is a simplification).

If you want to do something when the viewport is resized, utilize the native `resize` event:

angular.element($window).on('resize', function () {
    $scope.$apply(function () {
        // ... add your code here
    });
});

If the above method does not cover all instances of resizing that you need to monitor, you can continue with what you are currently doing and also trigger a `$digest()` on window resize:

angular.element($window).on('resize', function () {
    $scope.$digest();
});

However, keep in mind the potential performance consequences of binding functions to be executed during every digest cycle.

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

Hide the scroll bar in html/css while keeping the functionality of the arrows intact

Is there a way to remove the scroll bar but still be able to access overflown data using arrows? Any assistance would be greatly appreciated. Thank you in advance. ...

just require a signature showcased in a specific area

How can you achieve this? Displaying text on a radio as it is selected, ensuring only one option is shown and not revealed to others. https://i.stack.imgur.com/mNyQy.png I have added a red box around the text that should only appear in a specific locatio ...

The framework of AngularJS modules

As I delve into structuring multiple modules for our company's application, I find myself at a crossroads trying to design the most optimal architecture. Research suggests two prevalent approaches - one module per page or a holistic 'master' ...

The css values for component _nghost-c0 in an Angular application

Recently, I've been delving into Angular 5 and couldn't help but notice the peculiar html tags with ng generated attributes like _nghost-c0 and _nghost-c1... This got me wondering, what exactly do these attributes signify? [_nghost-c3] .employee ...

Implementing a button row and content alignment next to an image using Bootstrap or CSS

Ensure that the product detail page features a row with labels and buttons, positioned to the right of the image within Bootstrap columns. I have utilized Bootstrap 3 for this page layout. However, upon implementation, I encountered an issue whereby the b ...

Steps to incorporate a personalized design onto a card element within Material UI

As a JavaScript developer, I was tasked by my brother to create a simple webpage for his business. Admittedly, frontend design is not my strongest suit so I decided to utilize Material UI and added some CSS to paste everything together. Right now, I am wo ...

What is the best way to bridge the gap between the rows?

After combining the top and bottom blocks, I now have a gap in my layout. Is there a way to move this row up without causing any issues? I need assistance with resolving this problem using Bootstrap. <link rel="stylesheet" href="https://maxcdn.boots ...

What could be causing AngularJS to fail to send a POST request to my Express server?

I am currently running a Node Express server on localhost that serves a page with AngularJS code. Upon pressing a button on the page, an AngularJS controller is triggered to post a JSON back to the server. However, I am facing an issue where the post requ ...

Is it possible in Angular to generate a copy of a row within an ng-repeat loop?

In my coding method, I utilize ng-repeat to iterate through an array and pair each item with a value from a dropdown list. Check out this jsfiddle showcasing the method: https://jsfiddle.net/4zbvv5gq/4/ <header> <title>myTitle</title& ...

What could be causing me to not receive the prepackaged error messages from Angular in my WebStorm 8?

Having some trouble here... my angular errors are always so cryptic, like this: I usually manage to figure out the issue on my own, but I'm really hoping someone can offer guidance on how to get those nice error messages that angular supposedly displ ...

Transitioning the color of links in Firefox causes flickering when switching between the hover and visited state

I have been working on testing this code snippet in Firefox 49.0 on Linux Mint: a{ font-size:50px; color:gray; font-weight:1000; transition:color 1s; } a:hover{ color:black; } a:visited{ color:lightgray; } <a href="">VISITED LINK</a>&l ...

Another option for replacing <BR> tags with CSS styling

I am currently utilizing the br tag to insert line breaks in my website's faq section. Although the output is accurate, I'm exploring alternatives like implementing linebreak through CSS to enhance responsiveness. During my research, I came acros ...

What alternative methods can be utilized to refresh my Angular page without resorting to using location.reload()?

When it comes to this question, there appear to be two possible solutions: $scope.cancel = -> location.reload() or: $scope.cancel = -> $route.reload() The first option works effectively, however, it involves a full GET reques ...

Mastering the Art of Aligning Avatars: Effortless Right Alignment

Here's the updated version of the navigation bar: <nav class="navbar navbar-expand-md navbar-dark bg-dark static-top"> <button class="navbar-toggler" type="button" data-toggle="collapse"> ...

Manipulate elements by adding and removing classes sequentially based on an array

Previously, some had difficulty understanding my question. I have an array of variables representing the ids of 5 divs. My goal is to change the color of each div sequentially for a brief moment before reverting back, mimicking the behavior of traffic ligh ...

Getting the next sibling element with Selenium: A complete guide

Having trouble targeting a textbox after the label "First Name" in a list to enter a first name. Here's what I've tried: WebElement firstNameLocTry = driver.findElement(By.xpath("//label[text()='First Name']/following-sibling::d ...

Tips for maintaining the alignment of four buttons in a single row as the size of the screen changes

I'm creating a simple browser game as part of my web development learning process. I have a set of divs that represent a warrior, and at the head of the "div table" I have a group of 4 buttons arranged horizontally. However, when the screen size is re ...

Centering items in Material UI Grid

I'm currently grappling with understanding Material UI's grid system and implementing it in React.js, and I find it a bit perplexing. My goal is to center the spinner loader and text irrespective of viewport size. While I can manage to place the ...

What is the best way to verify a user's login status in AngularJS using $routeChangeStart event?

I am new to AngularJS and I need help checking if my user is logged in or not using $routeChangeStart. Controller angular.module('crud') .controller('SigninCtrl', function ($scope,$location,User,$http) { $scope.si ...

How can we add a class to a radio button using jQuery when it is checked, and remove the class when it

I'm looking for help with using jQuery to toggle between two radio buttons and display different divs based on the selection. jQuery(document).ready(function($) { if ($('#user_personal').is(':checked')) { $('.user_co ...