与ng-attr或ng-class一起使用的attribute-directive

时间:2014-08-21 21:03:22

标签: angularjs dynamic angularjs-directive

前言

我已经看到很多关于使用ng-attr和指令的问题,但我还没有看到这个具体案例正在实施。

代码& plunkr

http://bit.ly/1s6gWkD

用例

我正在尝试通过属性指令动态地将加载叠加层添加到目标DOM元素中。这个想法是,凭借拥有属性指令的目标DOM元素,DOM将覆盖附加到其子节点。

我从各个方面接近这一点,没有运气。因为这将在我们可能想要阻止某些UI而不是使用模态完全阻止应用程序的许多地方使用,我希望保持我们的模板清洁并动态附加它。

问题

  • 这是可能的(假设有一个指令生命周期事件来解决这个问题),BTW这就是我所说的动态方法
  • 如果不可能的话,我确实尝试了一些不太理想的“静态”方法,比如没有运气
    • ng-class =“{loadOverlay:hasOverlay}”
    • NG-ATTR的负载重叠= “hasOverlay”

观察

我确实意识到这种方法可能存在问题,因为一旦删除了属性,指令中可能没有生命周期事件就知道它被命令自行删除。我不太了解指令,知道是否是这种情况。

理想情况下我正在寻找

目标DOM元素没有叠加

enter image description here enter image description here

目标DOM元素w / overlay

enter image description here enter image description here

1 个答案:

答案 0 :(得分:2)

解决静态方法

在考虑了这个问题后,我认为有一个更通用的指令与“静态”相结合。方法是最好的。

plunkr解决方案

http://bit.ly/1toMCV9

.directive('loadOverlay', function() {

return {

  restrict: 'EA',

  scope: true,

  link: function(scope, element, attrs) {

    var id = 'nx-load-overlay-' + parseInt(Math.random() * 1000);

    function toggleOverlay(show) {
      if (show === true) {
        var d = '<div id="' + id + '" class="nx-load-overlay"><div class="nx-load-overlay-spinner"><span class="fa fa-cog fa-spin fa-3x"></span><br/><span style="font-weight:bold; font-size:larger;">loading</span></div></div>';
        element.append(d)
      } else {
        $('#' + id).remove()
      }
    }

    if (attrs.loadOverlay)
      scope.$watch(attrs.loadOverlay, toggleOverlay);

    else
      toggleOverlay(true)
  }
}
})