AngularJS指令中的元素高度

时间:2015-01-12 03:09:11

标签: javascript jquery css angularjs

我试图在一个简单的AngularJS应用程序中获取元素的高度。 见下文。我究竟做错了什么?线条包裹的高度应该不同,但不管我在"标签"中输入的是什么,我都会向我报告20。阵列。

此处可以执行以下代码,否则请参见下文。 http://js.do/code/49177

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <base href="/">

  <title>height of element in angularjs</title>

  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

  <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular-route.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

  <script type="text/javascript">
    'use strict';

    var app = angular.module('heightApp', ['ngRoute', 'routing']);

    app.controller('heightCtrl', ['$scope', function ($scope) {
      $scope.labels = [
        'Hi there, I\'m a div.',
        'Me too, I\'m also a div.',
        'Can you see me, because I certainly can\'t see myself. I don\'t even know my own height. Isn\'t that just crazy?'
      ];

    }]);    

    angular.module('routing', []).config(['$routeProvider', function($routeProvider) {
      $routeProvider
        .when('/', {
          templateUrl: 'height.html',
          controller: 'heightCtrl'
        });
    }]);

    angular.module('heightApp').directive('reportMyHeight', function() {
      return function (scope, el, attrs) {
          alert('offsetHeight = ' + el[0].offsetHeight);
        }
    })
  </script>

</head>

<body ng-app="heightApp">

<div class="container">
  <div ng-view></div>
</div>

</body>

<script type="text/ng-template" id="height.html">
  <div class="row">
    <div class="col-sm-4" report-my-height ng-repeat="lbl in labels">
      {{ ::lbl }}
    </div>
  </div>
</script>

</html>

2 个答案:

答案 0 :(得分:8)

您需要等到下一个摘要周期。当您在指令中立即执行此操作时,ng-repeat内的插值{{ ::lbl }}将不会扩展。您可以将其置于$timeout关闭applyDigest参数。

即示例:

angular.module('heightApp').directive('reportMyHeight', function($timeout) {
   return function (scope, el, attrs) {

      $timeout(init, false);

      //Initialization
      function init(){
        console.log('offsetHeight = ' + el[0].offsetHeight,  el.html());
      }

    }
});

<强> Plnkr

答案 1 :(得分:1)

确保获得元素高度的另一种方法是使用watch。

angular.module('heightApp').directive('reportMyHeight', function($timeout) {
  return function (scope, el, attrs) {
    scope.$watch('lbl', function(newval, oldval){
      alert(newval + '\n\n' + 'offsetHeight = ' + el[0].offsetHeight);
    });
  }
})

自您使用::以来,它只会被触发一次。