【问题标题】:angular custom directive inside ngif - setting its absolute son's widthngif 中的角度自定义指令 - 设置其绝对儿子的宽度
【发布时间】:2015-11-20 16:01:18
【问题描述】:

我有一个自定义的角度指令,我有条件地显示它,因为它在 ng-if 中。在我的自定义指令中,我显示了 html 元素,其中一个元素具有绝对定位。

我想将绝对元素的宽度设置为指令的根宽度。请注意,我不能将指令根的显示设置为相对的。

你会如何建议我实现这样的壮举?

更新: 这是一个jsfiddle - http://jsbin.com/qofolahani/edit?html,css,js,console,output

请注意,在链接函数中我还没有元素的 css 样式,因此宽度等于 0,这意味着我不能将它设置为子 div 的宽度。

【问题讨论】:

  • I cannot set the directive root's display to be relative. 为什么?
  • 因为如果指令本身在一个短容器内,我希望绝对元素尽可能高而不在 dom 中创建滚动条
  • 做个小提琴,不清楚,你想要什么..
  • 为什么不son.css('width', el.css('width'))
  • 好的,我刚刚创建了一个 js fiddle

标签: javascript html css angularjs


【解决方案1】:

你的问题是你使用restrict: E
浏览器不会将 getCalculatedStyle 方法绑定到非标准 DOM 实体。

将此指令更改为属性使用:

<div my-dir></div> 

和指令:

{
    restrict: 'A',
    link : function (scope, element) {
      element.addClass('my-dir');
      element.find('.my-dir-content').width(element.width());
    },
    template: '<div class="my-dir-content"></div>'
}

或者你应该只使用内部模板化的 div。
replace: false 可以帮助解决这个问题。

{
  restrict: 'E',
  link : function (scope, element) {
    var o = element.find('.my-dir');
    var i = o.find('.my-dir-content');
    i.width(o.width());
  },
  replace: false,
  template: '<div class="my-dir"><div class="my-dir-content"></div>/div>'
}

否则,替换父节点:

{
  restrict: 'E',
  link : function (scope, element) {
    var i = element.find('.my-dir-content');
    i.width(element.width());
  },
  replace: true,
  template: '<div class="my-dir"><div class="my-dir-content"></div>/div>'
}

JSBin Preview


奖励:
您需要这样的代码来更新窗口调整大小的宽度:

  $(window).on('resize', onResize);
  function onResize() {
    i.width(o.width());
  }
  scope.$on('$destroy', function(){
    $(window).off('resize', onResize);
  });

【讨论】:

  • 我明白了,但我真正的指令比这更复杂。它必须是一个元素。你能想到任何其他解决方法吗?
  • 你应该使用内部 div 容器然后:见编辑
  • 但是如果我的指令中有几个层次结构,绝对的儿子不是儿子,而是更多的后代。
  • Ask new question 为此。用相关的小提琴
  • 我似乎看不出提出新问题的意义,您提出了一个解决方案,我描述它太具体了。它在原始问题的范围内
【解决方案2】:

您需要在指令根目录中添加一个css样式并将此位置设置为relative,类似于

custom-directive {
   position: relative;
}

将根 html 元素设置为 position: relative 将允许内部 html 元素在引用指令时采用绝对位置。

然后就可以取内层html元素并设置

inner-html-element {
    position: absolute;
    width: 100%;
}

【讨论】:

  • 我不能使用相对定位
猜你喜欢
  • 2018-04-25
  • 2016-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 1970-01-01
  • 2017-03-17
相关资源
最近更新 更多