简体   繁体   中英

Resizing divs on window resize using AngularJS

I'm trying to use a directive to resize a few divs on my page (5 to be exact). They're all columns which I'd like to resize so they always stretch to the bottom of the window.

I used this as a guide: Window resize directive

Coming up with this:

app.directive('resize', ['$window', function($window) {
    return {
        link: function(scope, elem, attrs) {
            scope.onResize = function() {
                var padding = 30,
                    offset = elem.prop('offsetTop'),
                    height = $window.innerHeight - offset - padding;

                elem.css({height: height + 'px'});
            }
            scope.onResize();

            angular.element($window).bind('resize', function() {
                scope.onResize();
            })
        }
    }
}]);

I've given my divs the directive element identifier of "resize".

On load, it works great - all divs are correctly sized. But, on changing window size, only the last rendered div is resized. I'm guessing it's because the resize window event is being overwritten each time with the scope of each div in turn, and so by the time the page is loaded, the window resize event only refers to the last rendered div.

How would I go about it so the resize event applies to all divs and not just the last one?

While looking into a completely unrelated issue, I realised I just needed to set the scope:

app.directive('resize', ['$window', function($window) {
    return {
        scope: {},
        link: function(scope, elem, attrs) {
            ....
        }
    }
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM