Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  5] [ 4]  / answers: 1 / hits: 106509  / 12 Years ago, tue, february 5, 2013, 12:00:00

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?


More From » angularjs

 Answers
41

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).


[#80417] Sunday, February 3, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brockg

Total Points: 55
Total Questions: 104
Total Answers: 104

Location: Hungary
Member since Wed, Nov 9, 2022
2 Years ago
;