Angular.js:在页面加载设置元素高度 [英] Angular.js: set element height on page load
问题描述
我AngularJS新手。我想创建网格(使用 NG-电网),它高度依赖于窗口的高度,即。 $('。gridStyle')的高度($(窗口).height() - 100);
I'm AngularJS newbie. I want to create grid (using ng-grid) which height depends on window height ie. $('.gridStyle').height($(window).height() - 100);
我已经写指令:
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();
};
});
这工作得很好,当我调整浏览器窗口,但如果网站加载首次不适用的风格。我在哪里可以把code到initalize高度?
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?
推荐答案
我在你的岗位之际,我一直在寻找一个解决同样的问题我自己。我总结了以下解决方案使用基于一些职位的指令。你可以在这里尝试(尝试调整浏览器窗口): http://jsfiddle.net/zbjLh/2/
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/
查看:
<div ng-app="miniapp" ng-controller="AppController" ng-style="style()" resize>
window.height: {{windowHeight}} <br />
window.width: {{windowWidth}} <br />
</div>
控制器:
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我原本在一个控制器( http://jsfiddle.net/zbjLh/ )的工作,但是从随后的阅读发现这是从角的角度酷,所以我现在已经把它转换使用指令。
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.
重要的是,请注意真正
标记在监视功能的末尾,用于比较getWindowDimensions返回对象的平等(删除或更改为false如果不使用对象)。
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).
这篇关于Angular.js:在页面加载设置元素高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!