Javascript Angular.js:在页面加载时设置元素高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14703517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:40:29  来源:igfitidea点击:

Angular.js: set element height on page load

javascriptangularjs

提问by kolar

I'm AngularJS newbie. I want to create grid (using ng-grid) which height depends on window height ie. $('.gridStyle').height($(window).height() - 100);

我是 AngularJS 新手。我想创建高度取决于窗口高度的网格(使用ng-grid)。$('.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?

当我调整浏览器窗口的大小但第一次加载站点时不应用样式时,这很有效。我在哪里可以放置代码来初始化高度?

回答by Matty J

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/

我在为自己寻找解决同一问题的方法时看到了您的帖子。我使用基于许多帖子的指令将以下解决方案放在一起。您可以在这里尝试(尝试调整浏览器窗口的大小):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.

仅供参考,我最初让它在控制器(http://jsfiddle.net/zbjLh/)中工作,但从随后的阅读中发现,从 Angular 的角度来看,这并不酷,所以我现在已将其转换为使用指令。

Importantly, note the trueflag 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).

重要的是,请注意true'watch' 函数末尾的标志,用于比较 getWindowDimensions 返回对象的相等性(如果不使用对象,则删除或更改为 false)。

回答by Razan Paul

To avoid check on every digest cycle, we can change the height of the div when the window height gets changed.

为了避免检查每个摘要周期,我们可以在窗口高度改变时改变 div 的高度。

http://jsfiddle.net/zbjLh/709/

http://jsfiddle.net/zbjLh/709/

<div ng-app="miniapp" resize>
  Testing
</div>

.

.

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

回答by Engineer

angular.element(document).ready(function () {
    //your logic here
});

回答by Tony BenBrahim

A slight improvement to Bizzard's excellent answer. Supports width-offset and/or height-offset on the element, to determine how much will be subtracted from the width/height, and prevents negative dimensions.

对 Bizzard 的出色回答略有改进。支持元素上的宽度偏移和/或高度偏移,以确定将从宽度/高度中减去多少,并防止负尺寸。

 <div resize height-offset="260" width-offset="100">

directive:

指示:

app.directive('resize', ['$window', function ($window) {
    return function (scope, element) {
        var w = angular.element($window);
        var heightOffset = parseInt(element.attr('height-offset'));
        var widthOffset = parseInt(element.attr('width-offset'));
        var changeHeight = function () {
            if (!isNaN(heightOffset) && w.height() - heightOffset > 0)
                element.css('height', (w.height() - heightOffset) + 'px');
            if (!isNaN(widthOffset) && w.width() - widthOffset > 0)
                element.css('width', (w.width() - widthOffset) + 'px');
        };
        w.bind('resize', function () {
            changeHeight();
        });
        changeHeight();
    }
}]);

EditThis is actually a silly way of doing it in modern browsers. CSS3 has calc, which allows the calculation to be specified in CSS, like this:

编辑这在现代浏览器中实际上是一种愚蠢的做法。CSS3 有 calc,它允许在 CSS 中指定计算,像这样:

#myDiv {
 width: calc(100% - 200px);
 height: calc(100% - 120px);
}

http://caniuse.com/#search=calc

http://caniuse.com/#search=calc

回答by Hardik Varia

It seems you require the following plugin: https://github.com/yearofmoo/AngularJS-Scope.onReady

您似乎需要以下插件:https: //github.com/yearofmoo/AngularJS-Scope.onReady

It basically gives you the functionality to run your directive code after the your scope or data is loaded i.e. $scope.$whenReady

它基本上为您提供了在加载范围或数据后运行指令代码的功能,即 $scope.$whenReady

回答by Fabien

Combining matty-jsuggestion with the snippet of the question, I ended up with this code focusing on resizing the grid after the data was loaded.

matty-j建议与问题的片段相结合,我最终得到了这段代码,重点是在加载数据后调整网格的大小。

The HTML:

HTML:

<div ng-grid="gridOptions" class="gridStyle"></div>

The directive:

该指令:

angular.module('myApp.directives', [])
    .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) {

                // resize Grid to optimize height
                $('.gridStyle').height(newValue.h - 250);
            }, true);

            w.bind('resize', function () {
                scope.$apply();
            });
        }
    });

The controller:

控制器:

angular.module('myApp').controller('Admin/SurveyCtrl', function ($scope, $routeParams, $location, $window, $timeout, Survey) {

    // Retrieve data from the server
    $scope.surveys = Survey.query(function(data) {

        // Trigger resize event informing elements to resize according to the height of the window.
        $timeout(function () {
            angular.element($window).resize();
        }, 0)
    });

    // Configure ng-grid.
    $scope.gridOptions = {
        data: 'surveys',
        ...
    };
}

回答by timactive

My solution if your ng-grid depend of element parent(div, layout) :

如果您的 ng-grid 依赖于元素 parent(div, layout) 我的解决方案:

directive

指示

myapp.directive('sizeelement', function ($window) {
return{
    scope:true,
    priority: 0,
    link: function (scope, element) {
        scope.$watch(function(){return $(element).height(); }, function(newValue, oldValue) {
            scope.height=$(element).height();
        });
    }}
})

sample html

示例 html

<div class="portlet  box grey" style="height: 100%" sizeelement>
    <div class="portlet-title">
        <h4><i class="icon-list"></i>Articles</h4>
    </div>
    <div class="portlet-body" style="height:{{height-34}}px">
        <div class="gridStyle" ng-grid="gridOrderLine" ="min-height: 250px;"></div>
    </div>
</div>

height-34 : 34 is fix height of my title div, you can fix other height.

height-34 : 34 是我标题 div 的固定高度,你可以固定其他高度。

It is easy directive but it work fine.

这是一个简单的指令,但它工作正常。

回答by Yash Singla

$(document).ready(function() {
       scope.$apply(function() {
                applyHeight();
            });
});

This also ensures that all the scripts have been loaded before the execution of the statements. If you dont need that you can use

这也确保在执行语句之前已加载所有脚本。如果你不需要,你可以使用

$(window).load(function() {
       scope.$apply(function() {
                applyHeight();
            });
});