AngularJS watch element height change in directive
Asked Answered
M

0

0

I realize there were several similar questions, I checked them but they don't seem to cover my case. So I have a fluid flexbox-based layout. Most of the window is used by container block, that shrinks when his siblings appear. Basically something like

<body>
    <div class="menu"></div>
    <div class="contact"></div>
    <div class="container"></div>
</body>

the container height is not changed directly, it's recalculated by browser when I toggle other elements, such as menu.

I want to watch the container height and recalculate some elements in the directive. I watch for its height like this

scope.$watch(()=>parentElement.prop('offsetHeight'), resize);
resize=()=>{console.log('resize called');};

problem is the resize is triggered only on the next digest. so when I toggle the menu for the first time nothing happens, on the second the resize is called but with previous (first call) dimensions and so on.

I realize that it's most likely because the browser resize does not trigger the digest, but the functions that show the menu use $rootScope, so some digest call should occur.

Is there a way to properly watch for element dimensions in this case?

UPD: if I remove the watch filter and listen to every event, I get to resize function when I trigger the menu (obviously it's the rootScope caused call) but the parent element height is still old. Maybe there is a way to defer the watcher? ideally not by timeout but by some event.

Mancilla answered 7/9, 2016 at 13:50 Comment(6)
parent element is parentElement=element.parent(), which resolves to the containerMancilla
You should probably use api.jquery.com/resize .Dystrophy
I'd really like to avoid using jquery, especially for such minor issueMancilla
Did you see this thread? #21171107Kasten
Javascript also has a build in resize event: w3schools.com/jsref/event_onresize.asp for a no jquery solution.Dystrophy
I checked it, but watching on whatever parent element property has the same problem (gets called on next digest only) and binding to resize does nothing at allMancilla

© 2022 - 2024 — McMap. All rights reserved.