Angular 指令适用于内联样式,但不适用于 class

Angular directive works with inline style but not with class

我有这个指令:

angular.module('exampleApp').directive('exampleDirective', ['$document', '$window', function($document, $window) {
    return {
        restrict: 'E',
        scope: false,
        template: '<div class="foo"></div>',
        link: function($scope, $element, $attrs) {
            var targetElement = angular.element(document.querySelector($attrs['targetSelector']));
            console.log(targetElement.css('height'));
        }
   }
]);

这与此 html:

配合得很好
 <div id="div1" style="height: 100px">A div</div>
 <example-directive target-selector="#div1" />

因为在控制台中我看到:打印出“100px”

但是有了这个 html:

 <style>
      .div-example {
          height: 100px;
      }
 </style>

 <div id="div2" class="div-example">A div</div>
 <example-directive target-selector="#div2" />

基本相同但没有内联样式,指令根本不起作用。控制台正在打印:“”(空字符串)。

我该如何解决这个问题?
我试过了 scope: true 但也没用。
targetElement.css('height') 只适用于内联样式吗?

当您执行 .css('height') 时,jQuery 只能告诉您在元素的 style 属性 或属性中设置的值。

如果你想知道元素的实际高度,试试

targetElement[0].clientHeight

或 jQuery:

targetElement.height()

在这里看到差异解释得更好一点:https://api.jquery.com/height/