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

Angular.js: set element height on page load

本文关键字:设置 元素 高度 加载 js Angular      更新时间:2023-09-26

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

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

我看到你的帖子时,我正在为自己寻找解决同样问题的方法。我使用基于多个帖子的指令,制定了以下解决方案。您可以在此处尝试(尝试调整浏览器窗口的大小):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();
        });
    }
})

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

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

为了避免在每个摘要循环中进行检查,我们可以在窗口高度更改时更改div的高度。

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          
    }
})
angular.element(document).ready(function () {
    //your logic here
});

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

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

指令:

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();
    }
}]);

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

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

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

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

它基本上为您提供了在加载您的作用域或数据(即$scope)后运行指令代码的功能$whenReady

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

HTML:

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

指令:

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

控制器:

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',
        ...
    };
}

如果你的ng网格依赖于父元素(div,layout),我的解决方案是:

指令

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

示例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是我的标题div的固定高度,您可以固定其他高度。

这是一个简单的指令,但效果很好。

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

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

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