【问题标题】:container of directive has 0px height, 0px width - angularjs指令容器的高度为 0px,宽度为 0px - angularjs
【发布时间】:2015-09-01 17:17:06
【问题描述】:

通过以下方式创建指令时,元素本身 (<a-directive>) 的高度为 0px,宽度为 0px。 jsfiddle

 var myApp = angular.module('myApp', []).directive('aDirective', function () {
    return {
        template: '<div style="height:100px;width:100px;background-color:red;"></div>',
      restrict: 'E',
      link: function (scope, element, attrs) {
      }
    };
  });

还有html:

<a-directive></a-directive>

如何让 html 元素拥有其子维度?

编辑:

我只是在小提琴中看到它有一个维度。但在我的项目中,它通常没有。任何想法为什么会出现这种情况?

【问题讨论】:

  • 我想我找到了原因。模板中的
    position: absolute.

标签: css angularjs angularjs-directive


【解决方案1】:

您可以为指令添加 CSS。示例:

a-directive {
  display: block;
}

【讨论】:

  • 我同意这个解决方案。我遇到了同样的问题,根据我的观察,当您为指令元素设置显示(块或与您的上下文相关的任何其他内容)时,它会对高度/宽度变化做出反应。
【解决方案2】:

在指令的返回对象中添加replace:true,指令将替换 div。

【讨论】:

  • 这是一个很好的答案,但我喜欢如果你不这样做,它会让你的标记更具可读性。我认为有一个 W3C Layout 类,不同的 Element / HTMLElement 具体类继承自。我也知道本机 WebComponents API 允许继承某些 Element / HTMLElement 具体类。有人知道 Angular 是否有这样的东西吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-03
  • 1970-01-01
  • 2012-03-24
  • 2012-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多