【问题标题】:Can I apply a css class based on the $index and the length of an ng-repeat object?我可以根据 $index 和 ng-repeat 对象的长度应用 css 类吗?
【发布时间】:2015-04-06 05:20:44
【问题描述】:

我希望这在其他任何地方都没有得到回答。我正在尝试使用ng-class 创建一个规则:

  • 如果项目在转发器索引中为 $first,则显示 firstTagClass
  • 当该项目是中继器中的唯一项目时不显示
  • 不使用scope.objects.length(因为在这种特定情况下,scope.objects 不是数组而是对象)。

用例

可以作为裁剪头像图片并将它们保存在同一个容器中的一个很好的起点。

到目前为止...

我完成了第一个和第三个目标,但我被第二个卡住了。我尝试添加第二个条件!$last,但它不起作用。

<div 
  ng-repeat="object in objects" 
  ng-if="$index < 4 && object.id !== me.id" 
  ng-class="{firstTagClass: $first && !$last}">
</div>

有没有办法通过ng-class 实现我的所有目标,或者我应该构建一个自定义指令?

提前感谢您的帮助。

哈德里安

更新

我正在添加 Codepen:http://codepen.io/anon/pen/ZYaBjW

【问题讨论】:

    标签: javascript css angularjs angularjs-ng-repeat


    【解决方案1】:

    我找到了一个使用指令的答案。您可以通过在此处删除 $scope.objects 中的第三个对象来检查解决方案:http://codepen.io/anon/pen/LEOopR

    HTML

    我添加了block-style 指令并使用class 属性而不是ng-class,因为我选择在我的link 函数中使用element.removeClass()。删除一个类似乎更合乎逻辑,因为我的意图是让它成为例外而不是规则。

    <div ng-repeat="object in objects"
         class="firstTagClass"
         ng-if="$index < 4 && object.id !== me.id"
         position="{{index}}"
         block-style>
      {{object.id}}
    </div>
    

    JS

    blockStyle 指令的详细信息:

    restrict: 'A',
    link: function(scope, el, attrs){
      var objects = scope.objects;
      var me = scope.me;
      var userCount = Object.keys(objects).length;
      var position = parseInt(attrs.position);
    
      //assign hasMe attribute for objects collection with me object
      if(objects){
        for(var prop in objects){
          if(objects[prop].id === me.id){
            objects.hasMe = true;
          }
        }
      }
    
      //handle particular case of 1 object displayed
      if(userCount < 2 || userCount < 3 && objects.hasMe === true){
        el.removeClass('firstTagClass');
      }else if(position > 0){
        el.removeClass('firstTagClass');
      }  
    } // end of link function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-06
      • 2015-04-29
      • 2020-05-28
      • 1970-01-01
      • 2017-02-11
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多