2017-02-07 25 views
1

我正在尝试在web商店中使用CSS和AngularJS制作徽章计数器。我在Angular中有一个指令,它添加或删除实现“badgeDirective”的HTML元素的属性。就像这样:CSS内容attr()已设置,但未显示

angular.module('myApp') 
    .directive('badgeDirective', function($timeout){ 
    return function(scope, elem, attrs) { 
     $timeout(function() { 
      elem.addClass('badge-directive'); 
     }, 0); 
     scope.$watch(attrs.badgeDirective, function(newVal) { 
      if (newVal > 0) { 
       elem.attr('badge-counter', newVal); 
      } else { 
       elem.removeAttr('badge-counter'); 
      } 
     }); 
    } 
}); 

的HTML看起来像这样:

<md-icon class="material-icons" badge-directive="cart.length" 
aria-label="Cart" >remove_shopping_cart</md-icon> 

的CSS:

.badge-directive[badge-counter]:after { 
    background: #5da2e2; 
    border-radius: 7px; 
    color: #fff; 
    content: attr(badge-counter); 
    font-size: 10px; 
    font-weight: 600; 
    height: 14px; 
    line-height: 13px; 
    right: -1px; 
    padding: 0 6px; 
    position: absolute; 
    width: 12px; 
    text-align: center; 
    top: 13px; 
} 

当我运行的网站,我看到徽章到位,但没有任何迹象的实际计数器:

Badge counter without an actual counter that shows length of 'cart'

我参加了调试定睛一看,发现这一点:

The cart length is there. But not showing!

有人可以帮助我? 我不知道为什么价值没有显示...

+3

我不是100%肯定,但如果你使用自定义的HTML元素属性,是不是要求他们开始与““数据 - ”?如:“数据徽章计数器”。 – MateBoy

+0

您可以创建一个示例来演示您面临的问题吗?我在一个codepen中试用了你的css,它工作正常,所以这不是你的代码的问题。 http://codepen.io/anon/pen/ZLjRXy – dommmm

+0

您是否尝试过设置一些文本而不是计数器值来检查您的属性是否实际生成?请注意,如果值为0,那么它不存在 –

回答

1

下面是如何才能使其工作。

.material-icons[badge-directive]:after { 
 
    background: #5da2e2; 
 
    border-radius: 7px; 
 
    color: #fff; 
 
    content: attr(badge-counter); 
 
    font-size: 10px; 
 
    font-weight: 600; 
 
    height: 14px; 
 
    line-height: 13px; 
 
    right: -1px; 
 
    padding: 0 6px; 
 
    position: absolute; 
 
    width: 12px; 
 
    text-align: center; 
 
    top: 13px; 
 
} 
 

 

 

 
.material-icons { 
 
    display: block; 
 
    position: relative; 
 
    margin-bottom: 1rem; 
 
}
<md-icon class="material-icons" badge-directive="cart.length" 
 
aria-label="Cart" badge-counter="1">remove_shopping_cart</md-icon> 
 

 
<md-icon class="material-icons" aria-label="Cart" >remove_shopping_cart</md-icon>

+0

感谢您的建议,但它没有奏效。但通过一些测试,我管理它的工作。 'md-icon'位于'md-button'内。所以我把badgeDirective移到了按钮上。它的工作!有些东西告诉我,'md-icon'不适合放置柜台。 – ClydeFrog