mBo
mBo

Reputation: 155

tracking element width on window resize angularjs

I'm trying to build a directive that keeps track of the width of a container and changes it on window resizes. I've found a lot of directives that keep track of window resizing dynamically, but is it somehow possible to rewrite the directive to still fire every resize but instead of calculating the window width on every fire, calculate the width of a specific element? So far I've used:

app.directive('monitorWindow', ['$window', function ($window) {
    return {
        link: link,
        restrict: 'A'
    };
    function link(scope, element, attrs){
        scope.windowWidth = $window.innerWidth ;

        function onResize(){
            console.log("window width is: " + $window.innerWidth);
            // uncomment for only fire when $window.innerWidth change
            if (scope.windowWidth !== $window.innerWidth)
            {
                scope.windowWidth = $window.innerWidth;
                scope.$digest();
            }
        }

        function cleanUp() {
            angular.element($window).off('resize', onResize);
        }

        angular.element($window).on('resize', onResize);
        scope.$on('$destroy', cleanUp);
    }
}]);

Which keeps track of the window size and not of a specific div. I've found a directive that gets the element dimensions but doesn't update on resizing. Both of them next to eachother for testing: https://codepen.io/mbezema/pen/odBpPo

I use this as I'm building an svg graph inside a div that calculates points and lines based on a scope.width. If that changes the whole graph needs to change.

Upvotes: 0

Views: 572

Answers (1)

Drag13
Drag13

Reputation: 5988

In a perfect world you should use Resize Observer. But, right now it is still not ready for production because it is very limited with browsers (Chrome only)

So you can go this way and try to get some polyfills and when all browsers will support this feature you will get rid of the polyfill or try to find something else like this standalone lib or this JQuery plugin

One note. You also can listen on window resize and each time check div's width, but is not 100% correct solution because width of the div can be changed without change the width of the window.

Hope this helps.

Upvotes: 1

Related Questions