Angular.js Use a preliminary introduction ng-class

本文介绍了AngularJS中ng-class指令的三种常见使用方法:通过scope变量绑定、通过对象数组绑定以及通过key/value键值对绑定。同时,还展示了如何在实际项目中利用ng-class结合ng-repeat来实现表格行的选择效果。

angular.js ng-class 使用

ng-class 常见三种使用方式:

  • 通过 scope 绑定
//1、通过$scope绑定(不推荐):
function ctrl($scope) { 
    $scope.className = "selected";
}

<div class="{{className}}"></div> 
  • 2、通过对象数组绑定:
function ctrl($scope) { 
    $scope.isSelected = true;
}

<div ng-class="{true:'selected',false:'unselected'}[isSelected]"></div> 

当isSelected为true时,增加selected样式;当isSelected为false时,增加unselected样式。

  • 通过key/value键值对绑定:
function ctrl($scope) { 
    $scope.isA = true;
    $scope.isB = false;
    $scope.isC = false;
}

<div ng-class="{'A':isA,'B':isB,'C':isC}"></div>

当isA为true时,增加A样式;当isB为true时,增加B样式;当isC为true时,增加C样式。

  • 通过ng-repeat 绑定
.selected {background-color: lightgreen;}
<html ng-app="myApp">
 <head>
  <title>CSS实例3</title>
  <link rel="stylesheet" type="text/css" href="css/menu03.css" />
 </head>
 <body>
  <table ng-controller="RestaurantTableController">
   <tbody>
    <tr ng-repeat="restaurant in directory" ng-click="selectRestaurant($index)" ng-class="{selected: $index==selectedRow}">
     <td>{{restaurant.name}}</td>
     <td>{{restaurant.cuisine}}</td>
    </tr>
   </tbody>
  </table>
  <script src="lib/angular/angular.js"></script>
    $scope.directory=[{name:'The Handsome Heifer',cuisine: 'BBQ'},
            Fine Fish',cuisine: 'Seafood'}];
      $scope.selectRestaurant=function(row) {$scope.selectedRow=row;};});</script>
 </body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值