【问题标题】:Angular.js: set element height on page loadAngular.js:在页面加载时设置元素高度
【发布时间】:2013-01-20 03:25:45
【问题描述】:

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

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

【问题讨论】:

  • 尝试在指令底部使用 $timeout 、 $timeout(applyHeight)。
  • $timeout(applyHeight) 更改样式但不幸的是网格没有刷新
  • 仅供参考,如果您的应用程序不是很小,将$apply 绑定到'resize' 事件是一个糟糕的主意。
  • 作为对@Fresheyeball 信息的补充,resize 在调整窗口大小时每秒可触发 20-50 次以上。小心使用。

标签: javascript angularjs


【解决方案1】:

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

【讨论】:

  • $watch一个函数不是很糟糕吗?据我了解,scope.getWindowDimensions() 将在每个 $digest 循环中被调用,即使窗口没有调整大小。
  • 据我了解,为了一次观看多个值(即窗口的“宽度”和“高度”),您需要观看一个函数(因此需要将监视功能标志(最后一个参数)设置为“真”))。如果您只想查看一个维度或一个值,则不需要函数。
  • @n1313 观看功能完全正常
  • @MattyJ 你可以观看动态生成的“{a:b, c:d}” 表达式,还有 $watchGroup 以 1.3 的角度出现
【解决方案2】:

为了避免检查每个摘要循环,我们可以在窗口高度发生变化时更改 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          
    }
})

【讨论】:

    【解决方案3】:
    angular.element(document).ready(function () {
        //your logic here
    });
    

    【讨论】:

      【解决方案4】:

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

       <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

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          【解决方案6】:

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

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

          【讨论】:

          • 你在哪里添加了 resize directive
          【解决方案7】:

          如果您的 ng-grid 依赖于元素父级(div,布局),我的解决方案:

          指令

          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 的固定高度,你可以固定其他高度。

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

          【讨论】:

            【解决方案8】:
            $(document).ready(function() {
                   scope.$apply(function() {
                            applyHeight();
                        });
            });
            

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

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

            【讨论】:

            • 两种解决方案均无效(Chrome 开发工具中的 .gridStyle 高度不会改变)。
            猜你喜欢
            • 1970-01-01
            • 2016-03-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多