使用 Angular ng-if 旋转样式

Rotate Styles using Angular ng-if

仍在学习 angular,但在旋转样式时遇到问题。最后,我希望第一个记录是蓝色的,第二个是白色的,第三个是蓝色的,第四个是白色的,等等...

现在我的订单是(不正确的): 记录 1 蓝色 记录3蓝色 记录2白 记录4白

任何想法可能是什么问题?

HTML

<div id="dashboard" style="width: 1100px;" ng-controller="controller4">

<div class="blue" ng-repeat="metrics in dashboard" ng-if="($index % 2 == 0)">
 <div align="center">
  <h3>{[{metrics.value}]}</h3>
  <span class=dashboardtext>{[{metrics.name}]}</span>
 </div>
</div>

<div class="white" ng-repeat="metrics in dashboard" ng-if="($index % 2 != 0)">
 <div align="center">
  <h4>{[{metrics.value}]}</h4>
  <span class=dashboardtext>{[{metrics.name}]}</span>
 </div>
</div>


</div>

JS

var dashboard = [

{

value: 15, 
name: "Total Completed"

},


{

value: 1200, 
name: "Additional Widgets Sold"

},


{

value: 16, 
name: "Projects"

},

{

 value: 5, 
 name: "Average Days"

 }


];




myApp.controller('controller4', function($scope) {


$scope.dashboard = dashboard;



});

ng-class-even & ng-class-odd 指令完全符合您的需要。

ng-class-even -> Add a class value to DOM classList object when $index is even

ng-class-odd -> Add a class value to DOM classList object when $index is odd

标记

<div ng-class="'blue'" ng-class-odd="'white'" ng-repeat="metrics in dashboard">
 <div align="center">
  <h3>{[{metrics.value}]}</h3>
  <span class=dashboardtext>{[{metrics.name}]}</span>
 </div>
</div>

对于简单的even/odd,可以使用ng-class-even 和ng-class-odd 属性。如果您的情况更复杂且值更多,请使用以下解决方案。

创建过滤器并在 class 属性中使用它。

app.filter("classFilter", function () {
            return function (input) {
                var $class = "";
                switch(input % 2){
                    case 0:
                        $class = "blue";
                        break;
                    case 1:
                        $class = "white";
                        break;
                }
                return $class;
            }
        });

那么在你的HTML中,你会

<div class="$index | classFilter" ng-repeat="metrics in dashboard">
 <div align="center">
  <h3>{[{metrics.value}]}</h3>
  <span class=dashboardtext>{[{metrics.name}]}</span>
 </div>
</div>