使用ng-class在AngularJS中有条件地选择一个类

时间:2015-05-04 10:51:32

标签: angularjs-directive

我在数组中有两个类,如下所示

$scope.userClasses = ["user-dashboard-dark", "user-dashboard-light"];

我的HTML代码是

<div class="row">
    <div ng-click="userClick(user)" class="col-lg-3 col-md-3 col-sm-4 col-xs-12" ng-repeat="user in usersList" style="cursor:pointer;">
        <div class="panel widget" ng-class="userClasses">
            <div class="panel-body">
                <div class="row row-table">
                    <div class="col-xs-4 text-center">
                        <img src="{{user.image || 'app/img/user/avatar03.png'}}" alt="Image" class="img-thumbnail img-circle img-responsive thumb64" />
                    </div>
                    <div class="col-xs-8 text-center">
                        <h4 class="m0">{{user.userName}}</h4>
                        <em class="fa fa-envelope fa-fw"></em>
                        <span><small>{{user.email}}</small></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

我想第一次使用头等舱(用户仪表板 - 黑暗),其余的我想使用第二类(用户仪表板 - 灯光)

2 个答案:

答案 0 :(得分:0)

可以试试这个:

<div ng-class="userClasses[0]"> {{user.userName}} </div>

<div ng-class="userClasses[1]"> {{user.email}} </div>

答案 1 :(得分:0)

在ng-repeat中使用变量$ first。如果重复元素在迭代器中是第一个,则$ first为true。 您的HTML代码应如下所示:

<div class="row">
   <div ng-click="userClick(user)" class="col-lg-3 col-md-3 col-sm-4 col-xs-12" ng-repeat="user in usersList" style="cursor:pointer;">
      <div class="panel widget" ng-class="{'user-dashboard-dark' :$first, 'user-dashboard-light': !$first }">
         <div class="panel-body">
            <div class="row row-table">
               <div class="col-xs-4 text-center">
                  <img src="{{user.image || 'app/img/user/avatar03.png'}}" alt="Image" class="img-thumbnail img-circle img-responsive thumb64" />
               </div>
               <div class="col-xs-8 text-center">
                  <h4 class="m0">{{user.userName}}</h4>
                  <em class="fa fa-envelope fa-fw"></em>
                  <span><small>{{user.email}}</small></span>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>

如果您坚持要从数组中应用类,那么在控制器中定义一个函数,该函数根据$ first返回正确的类:

  $scope.isFirstRow = function(first){
    return (first ? $scope.userClasses[0] : $scope.userClasses[1]);
  }

并在你的HTML中:

<div class="panel widget" ng-class="isFirstRow($first)">