7-acga
Last Updated: February 25, 2016
·
10.29K
· dustinrjo
Img 2769 5

Simple AngularJS Directive to Match Window Height

Here is a basic coffee script directive for Angular JS to match the window height of any object with the attribute 'match-window-height'

app.directive 'matchWindowHeight', ($timeout, $window) ->
    (scope, el, attrs) ->

    setHeight = () ->
      el.css("height", $window.innerHeight+"px")

    setHeight()

    $timeout ->
      setHeight()

    angular.element($window).on "resize", setHeight

    cleanup = ->
      angular.element($window).off "resize", setHeight

    el.on '$destroy', cleanup

Here's the tl;dr

To walk through what is going on, this code looks for objects on the DOM that have the attribute value (or I suppose also the class name) 'match-window-height'.

app.directive 'matchWindowHeight', ($timeout, $window) ->

This is typical because Angular takes the camel case name of the directive set in the first line and reads it to a dash delimited string. We pass the $timeout and $window into the constructor as dependencies because we use them later in the directive.

(scope, el, attrs) ->

The constructor returns a function that has the scope, el', and attrs which are just conventional names you could call these a, b, c or whatever but the three parameters available will be the scope, the element and the attributes of the DOM element targeted by the directive.

setHeight = () ->
  el.css("height", $window.innerHeight+"px")

Our setHeight function uses Angulars element implementation of jqLite to attach the style property height with a value returned by $window.innerHeight, Angular's internal alias for window.innerHeight.

We then run setHeight when the directive first matches

setHeight()

and inside of a $timeout because the DOM rendering can happen asynchronously in some edge cases

$timeout ->
  setHeight()

and we bind setHeight to the $window service's resize event.

angular.element($window).on "resize", setHeight

We create a cleanup function because we will want to remove the listeners when the element is destroyed.

cleanup = ->
    angular.element($window).off "resize", setHeight

el.on '$destroy', cleanup
Say Thanks
Respond

1 Response
Add your response

16803
Ad68e449defb6d25238dc95088cfcbaf

this is EXACTLY what I needed. Thanks for the concise explanation!

over 1 year ago ·