如何在angular js中获取窗口高度

How to get window height in angular js

本文关键字:获取 窗口 高度 js angular      更新时间:2024-05-28

我正在使用iframe,使用带有离子框架的angularjs来显示内容。在这里,我需要将窗口高度作为iframe高度,所以我使用了

  $scope.iframeHeight = window.innerHeight;

但是,我得到的屏幕只有1/4。

这是我迄今为止所尝试的。

index.html

<!DOCTYPE html>
<html ng-app="ionicApp">
    <head>
    <!-- ionic/angularjs CSS -->
    <link href="css/ionic.css" rel="stylesheet">
    <link href="css/ionic-custom.css" rel="stylesheet">
    <!-- ionic/angularjs js bundle -->
    <script type="text/javascript" src="js/ionic.bundle.js"></script>
    <script>
    angular.module('ionicApp', ['ionic'])
.controller('MainCtrl', function($scope) { 
  $scope.iframeHeight = window.innerHeight;
});
    </script>
    </head>
    <body ng-controller="MainCtrl">
        <iframe src="http://stackoverflow.com" ng-style="{height:iFrameHeight}" id="iframeid" width="100%" ></iframe>   
    </body>
</html>

我是不是错过了什么?

主要问题:您需要将'px'单位添加到window.innerHeight数字中。第二个,变量名是iframeHeight而不是iFrameHeight。固定表达式将看起来像:

ng-style="{height: iframeHeight + 'px'}"

演示:http://plnkr.co/edit/NdQB5afQT7kMkf27k7wg?p=preview

窗口对象虽然全局可用,但在angular文档中作为参考存在可测试性问题https://docs.angularjs.org/api/ng/service/$window。看起来这对你的代码来说不是问题,但为了更好的实践,你可以注入一个$window服务,然后引用它,当然还有底部的"px"问题。

   angular.module('ionicApp', ['ionic']) 
    .controller('MainCtrl', function($scope, $window) { 
   $scope.iframeHeight = $window.innerHeight;
     });

稍后,如前所述;

  ng-style="{height: iframeHeight + 'px'}"

由于AngularJS本身包含jQuery的一小部分,您可以使用:

// Returns height of browser viewport
$scope.iframeHeight = $(window).height();

// Returns height of HTML document
$scope.iframeHeight = $(document).height();

使用角度计算窗口高度

$scope.screenHeight = '';
$scope.calculateoriginalWidth = function() {
    var width = $window.innerWidth;
    $rootScope.originalWidth = width;
}
$scope.calculateScreenHeight = function() {
    var height = $window.innerHeight;
    var width = $window.innerWidth;
    var subheight = 0;
    var headerheight = document.getElementById('headerTitle1');
    var headerheight2 = document.getElementById('headerTitle2');
    if (headerheight) {
        subheight += headerheight.offsetHeight;
    }
    if (headerheight2) {
        subheight += headerheight2.offsetHeight;
    }
    $scope.screenHeight = height - subheight - 20;
    $rootScope.screenHeight = $scope.screenHeight;
    $scope.screenWidth = width;
    $rootScope.screenWidth = $scope.screenWidth;
}
var reg = $scope.$on('screenResize', function($evt, args) {
    $scope.calculateScreenHeight();
    $scope.$apply();
})
window.onresize = function(event) {
    $scope.$apply(function() {
    $scope.calculateScreenHeight();
    })
};
$scope.calculateScreenHeight();
$scope.calculateoriginalWidth();

您需要在angular中添加所需的依赖项才能使用此代码。希望这能帮助你计算窗户的高度。