perminder-klair
5/1/2014 - 11:41 AM

Resize container as Window size (accepts percentage) for AngularJs

Resize container as Window size (accepts percentage) for AngularJs

'use strict';

/**
 * Usage: ng-style="style()" resize heightpercetange="50" widthpercetange="50"
 */
angular.module('app')
    .directive('resize', function ($window) {

        return {
            restrict: 'A',

            link: function (scope, elem, attrs) {

                var w = angular.element($window);

                scope.getWindowDimensions = function () {
                    return { 'h': w.height(), 'w': w.width() };
                };

                scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {

                    var newHeight = newValue.h;
                    if (typeof attrs.heightpercetange !== "undefined") {
                        newHeight = (attrs.heightpercetange / 100) * newValue.h;
                    }
                    elem.css('height', newHeight + 'px');

                    var newWidth = newValue.w;
                    if (typeof attrs.widthpercetange !== "undefined") {
                        newWidth = (attrs.widthpercetange / 100) * newValue.h;
                    }
                    elem.css('width', newWidth + 'px');

                }, true);

                w.bind('resize', function () {
                    scope.$apply();
                });
            }
        };

    });