kol*_*lar 43 javascript angularjs
我是AngularJS的新手.我想创建网格(使用ng-grid),其高度取决于窗口高度,即.$('.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();
};
});
Run Code Online (Sandbox Code Playgroud)
这在我调整浏览器窗口大小时很有效,但是第一次加载网站时不应用样式.我在哪里可以将代码放入高度?
Mat*_*y J 81
我遇到了你的帖子,因为我正在为自己寻找同样问题的解决方案.我使用基于许多帖子的指令将以下解决方案放在一起.你可以在这里试试(尝试调整浏览器窗口的大小):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>
Run Code Online (Sandbox Code Playgroud)
控制器:
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();
});
}
})
Run Code Online (Sandbox Code Playgroud)
仅供参考我最初在控制器(http://jsfiddle.net/zbjLh/)中工作,但是从后来的阅读中发现,从Angular的角度来看这是不冷却的,所以我现在已将其转换为使用指令.
重要的是,请注意true'watch'函数末尾的标志,用于比较getWindowDimensions返回对象的相等性(如果不使用对象,则删除或更改为false).
为了避免检查每个摘要周期,我们可以在窗口高度变化时更改div的高度.
http://jsfiddle.net/zbjLh/709/
<div ng-app="miniapp" resize>
Testing
</div>
Run Code Online (Sandbox Code Playgroud)
.
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
}
})
Run Code Online (Sandbox Code Playgroud)
angular.element(document).ready(function () {
//your logic here
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
103853 次 |
| 最近记录: |