Source:viewport-info.directive.js

(function () {
    'use strict';
    // Viewport Information
    angular
        .module('mohistory')
        .directive('viewportInfo', viewportInfo);
    viewportInfo.$inject = ['$window', '$transitions', '$timeout', '$rootScope'];
    /**
     * Encapsulates listeners for window resize and scroll events. This information
     * is stored on the rootScope so other directives can access it later.
     * @memberof mohistory
     * @name viewportInfo
     * @ngdoc directive
     */
    function viewportInfo($window, $transitions, $timeout, $rootScope) {
        var directive = {
            link: viewportInfoLink,
            restrict: 'A',
        };
        return directive;
        /**
         * Link function which adds event listeners to the angular Window object 
         * @memberof viewportInfo
         * @function viewportInfoLink
         * @param {String} scope an AngularJS scope object.
         * @param {String} element the jqLite-wrapped element that this directive matches.
         * @param {String} attrs a hash object with key-value pairs of normalized attribute 
         * names their corresponding attribute values.
         */
        function viewportInfoLink(scope, element, attrs) {
            $rootScope.viewport = {
                height: $window.innerHeight,
                width: $window.innerWidth,
                scrollX: $window.scrollX,
                scrollY: $window.scrollY,
            };
            angular.element($window).on('resize', updateDimensions);
            angular.element($window).on('scroll', updateScrollPos);
            scope.$on('$destroy', function () {
                angular.element($window).off('resize', updateDimensions);
                angular.element($window).off('scroll', updateScrollPos);
            });
            /** 
             * Update the height and width stored on the viewport object.
             * @function updateDimensions
             * @memberof viewportInfoLink
             */
            function updateDimensions() {
                $rootScope.viewport.height = $window.innerHeight;
                $rootScope.viewport.width = $window.innerWidth;
                $rootScope.$apply();
            }
            /** 
             * Update the x and y scroll positions stored on the viewport object.
             * @function updateScrollPos
             * @memberof viewportInfoLink
             */
            function updateScrollPos() {
                $rootScope.viewport.scrollX = $window.scrollX;
                $rootScope.viewport.scrollY = $window.scrollY;
                $rootScope.$apply();
            }
        }
    }
})();