angularjs 頁面自適應(yīng)高度的方法
需求
在angularjs構(gòu)建的業(yè)務(wù)系統(tǒng)中,通過ui-view路由實現(xiàn)頁面跳轉(zhuǎn),初始化進(jìn)入系統(tǒng)后,右側(cè)內(nèi)容區(qū)域需要自適應(yīng)瀏覽器高度。
實現(xiàn)方案
- 在ui-view所在的Div添加directive,directive中通過element.css初始化計算div的高度,動態(tài)更新div高度
- directive監(jiān)聽($$watch)angular的$digest,實時獲取body高度,動態(tài)賦值model或element.css改變
方案1:添加directive和element.css自適應(yīng)高度
1.創(chuàng)建directive
define([ "app" ], function(app) {
app.directive('autoHeight',function ($window) {
return {
restrict : 'A',
scope : {},
link : function($scope, element, attrs) {
var winowHeight = $window.innerHeight; //獲取窗口高度
var headerHeight = 80;
var footerHeight = 20;
element.css('min-height',
(winowHeight - headerHeight - footerHeight) + 'px');
}
};
});
return app;
});
2.div元素添加directive
<div ui-view auto-height></div>
3.效果圖
原界面:右側(cè)區(qū)域的高度為自適應(yīng)內(nèi)容,導(dǎo)致下方存在黑色的背景色

調(diào)整后:右側(cè)區(qū)域的高度自適應(yīng)瀏覽器

方案2:$watch監(jiān)聽body高度,賦值改變高度
1.創(chuàng)建resize directive
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();
});
}
})
2.在div元素上增加resize directive
<div ng-app="miniapp" ng-controller="AppController" ng-style="style()" resize>
window.height: {{windowHeight}} <br />
window.width: {{windowWidth}} <br />
</div>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
AngularJS 基礎(chǔ)ng-class-even指令用法
本文主要介紹AngularJS ng-class-even 指令,這里整理了ng-class-even基礎(chǔ)知識資料,并附實例代碼和效果圖,學(xué)習(xí)AngularJS指令的朋友可以看下2016-08-08
Angular 根據(jù) service 的狀態(tài)更新 directive
Angular JS (Angular.JS) 是一組用來開發(fā)Web頁面的框架、模板以及數(shù)據(jù)綁定和豐富UI組件。本文給大家介紹Angular 根據(jù) service 的狀態(tài)更新 directive,需要的朋友一起學(xué)習(xí)吧2016-04-04

