I'm AngularJS newbie. I want to create grid (using ng-grid) which height depends on window height ie. $('.gridStyle').height($(window).height() - 100);
I have written directive:
app.directive('resize', function($window) { return function(scope, element) { function applyHeight() { scope.height = $window.innerHeight; $('.gridStyle').height(scope.height - 100); } angular.element($window).bind('resize', function() { scope.$apply(function() { applyHeight(); }); }); applyHeight(); }; });
This works well when I resize browser window but style is not applied when site is loaded for the first time. Where can I put code to initalize height?
I came across your post as I was looking for a solution to the same problem for myself. I put together the following solution using a directive based on a number of posts. You can try it here (try resizing the browser window): http://jsfiddle.net/zbjLh/2/
View:
<div ng-app="miniapp" ng-controller="AppController" ng-style="style()" resize> window.height: {{windowHeight}} <br /> window.width: {{windowWidth}} <br /> </div>
Controller:
var app = angular.module('miniapp', []); function AppController($scope) { /* Logic goes here */ } app.directive('resize', function ($window) { return function (scope, element) { var w = angular.element($window); scope.getWindowDimensions = function () { return { 'h': w.height(), 'w': w.width() }; }; scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) { scope.windowHeight = newValue.h; scope.windowWidth = newValue.w; scope.style = function () { return { 'height': (newValue.h - 100) + 'px', 'width': (newValue.w - 100) + 'px' }; }; }, true); w.bind('resize', function () { scope.$apply(); }); } })
FYI I originally had it working in a controller (http://jsfiddle.net/zbjLh/), but from subsequent reading found that this is uncool from Angular's perspective, so I have now converted it to use a directive.
Importantly, note the true
flag at the end of the 'watch' function, for comparing the getWindowDimensions return object's equality (remove or change to false if not using an object).
To avoid check on every digest cycle, we can change the height of the div when the window height gets changed.
http://jsfiddle.net/zbjLh/709/
<div ng-app="miniapp" resize> Testing </div>
.
var app = angular.module('miniapp', []); app.directive('resize', function ($window) { return function (scope, element) { var w = angular.element($window); var changeHeight = function() {element.css('height', (w.height() -20) + 'px' );}; w.bind('resize', function () { changeHeight(); // when window size gets changed }); changeHeight(); // when page loads } })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With