在AngularJS中不使用JQuery获取多个元素的高度

时间:2016-03-24 16:00:56

标签: javascript html angularjs

Angular相当陌生,仍然试图围绕一些事情。 我需要在仪表板上获得多个项目的高度。我看到了这个答案: Get HTML Element Height without JQuery in AngularJS 但是,我无法弄清楚如何使它适用于多个项目。当然,我不需要为每个元素编写单独的指令。 所以玩这个Plunker,我将html更改为下面的内容,但两个元素的值都相同。

HMM

的script.js:

angular.module('myModule', [])
  .directive('myDirective', function($timeout) {
    return {
        restrict: 'A',
        link: function(scope, element) {
            scope.height = element.prop('offsetHeight');
            scope.width = element.prop('offsetWidth');
        }
    };
  })
;

和html:

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@*" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myModule">

    <h1 my-directive>Hello Plunker! width: {{width}}, height: {{height}}
    </h1>
    <h3 my-directive>Smaller Hello Plunker! width: {{width}}, height: {{height}}
    </h3>
  </body>

</html>

2 个答案:

答案 0 :(得分:0)

指令没有范围,因此它们将值存储在$rootScope上。这些值反映了要执行的最后一个指令的高度和宽度。修复您的指令,使用继承范围或隔离范围

angular.module('myModule', [])
  .directive('myDirective', function($timeout) {
    return {
        restrict: 'A',
        //set scope to inherited
        scope: true,
        //OR use isolate scope
        //scope: {},
        link: function(scope, element) {
            scope.height = element.prop('offsetHeight');
            scope.width = element.prop('offsetWidth');
        }
    };
  })
;

通过设置scope属性,$compile服务将为要存储的指令创建新范围(继承隔离)指令特有的值。

有关指令范围的更多信息,请参阅AngularJS Comprehensive Directive API -- scope

答案 1 :(得分:0)

我发现这个脚本非常有用

https://github.com/pocesar/angular-track-height