AngularJS watch element height change in directive

2019-09-11 01:52发布

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.

0条回答
登录 后发表回答