angular學習筆記(九)-css類和樣式3

詩&遠方發表於2014-05-09

再來看一個選擇li列表的例子:

點選li中的任意項,被點選的li高亮顯示:

<!DOCTYPE html>
<html ng-app>
<head>
  <title>6.3css類和樣式</title>
  <meta charset="utf-8">
  <script src="../angular.js"></script>
  <script src="script.js"></script>
  <style type="text/css">
    li.cur {
      background:#C0DCC0
    }
  </style>
</head>
<body>
<div ng-controller = "Restaurant">
  <ul>
    <li ng-repeat="restaurant in restaurants" ng-class="{cur:$index==selRow}" ng-click="choose($index)">
      <span>{{restaurant.name}}</span><span>{{restaurant.food}}</span><span>{{restaurant.price}}</span>
    </li>
  </ul>
</div>
</body>
</html>
function Restaurant ($scope){
    $scope.selRow = null;
    $scope.restaurants = [
        {"name":"happy lemon","food":"greenTea","price":"¥15"},
        {"name":"coco","food":"milkTea","price":"¥10"},
        {"name":"good fruit","food":"fruits","price":"¥20"}
    ];
    $scope.choose = function(i){
        $scope.selRow = i
    }
}
ng-class="{cur:$index==selRow}":

在這裡,ng-class屬性的cur類名,繫結表示式 $index==selRow,
然後給每個li繫結點選事件回撥,點選任意li,就把selRow的值變為$index.這樣,當前被點選的項就會被新增類名cur,高亮顯示.
這裡可以看到,angular繫結的事件回撥,可以在執行的時候傳入引數

原始狀態:

點選第二項:



相關文章