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.

1
<div resizable ng-style="{ width: windowWidth, height: windowHeight }" ></div>

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.

directives/resizable.coffee
1
2
3
4
5
6
7
8
9
10
11
App.directive 'resizable', ($window) ->
  ($scope) ->
    $scope.initializeWindowSize = ->
      $scope.windowHeight = $window.innerHeight
      $scope.windowWidth  = $window.innerWidth

    $scope.initializeWindowSize()

    angular.element($window).bind 'resize', ->
      $scope.initializeWindowSize()
      $scope.$apply()
directives/resizable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
App.directive('resizable', function($window) {
  return function($scope) {
    $scope.initializeWindowSize = function() {
      $scope.windowHeight = $window.innerHeight;
      return $scope.windowWidth = $window.innerWidth;
    };
    $scope.initializeWindowSize();
    return angular.element($window).bind('resize', function() {
      $scope.initializeWindowSize();
      return $scope.$apply();
    });
  };
});
Toggle coffeescript/javascript

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.

Comments

Copyright © 2014 - Anthony Estebe -