Window Resize Event With Angular
I still working with Angular and yesterday I needed to know when the window is resized to update a grid (I will probably do another article for this). The behavior expected is: when I resize the window, I want to resize my div (or any other tag).
So for this, once again the directives will be very useful. My goal is to just have one argument to give to my element who need to listen the window resize event like that.
You can notice, I used the resizable attribute, then just a style to have like height = window height and width = window width.
So now we know what we want. Let’s create the directive to be able to do that.
1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6 7 8 9 10 11 12 13
We have a simple directive with only one function inside (the controller). In this controller we create a function to initialize windowHeight and windowWidth (accessible from the scope) with the dimensions of the window then we initialize them calling this function.
The magic happens on the last 3 lines. We create a new angular element from the window, like that we can bind the resize event and when this event is triggered, we just have to:
- get new values of the window with the initializeWindowSize function
- reapply the scope to refresh the template with the last dimensions of the window
Now everytime you want to access your windowHeight and windowWidth you just have to add the resizable attribute.