2014-01-10 32 views
0

myController的:

$scope.items = [ 
{name: 'item 1', description: 'desc001'}, 
{name: 'item 2', description: 'desc002'}, 
{name: 'item 3', description: 'desc003'},] 

$scope.selectRow = function (index) { 
    $scope.selectedRow = index; 
} 

CSS:

.select { 
     background-color: lightgreen; 
    } 

HTML 1:

<div ng-controller="myController"> 
<table> 
<tr ng-repeat="item in items" ng-click='selectRow($index)' ng-class="{select:$index == selectedRow}"> 
    <td>{{item.name}}</td> 
    <td>{{item.description}}</td> 
</tr> 
</table> 

HTML 2:

<div ng-controller="myController"> 
<table> 
<tr ng-repeat="item in items" ng-click='selectedRow = $index' ng-class="{select:$index == selectedRow}"> 
    <td>{{item.name}}</td> 
    <td>{{item.description}}</td> 
</tr> 
</table> 

爲什麼HTML-1的作品,但HTML-2無法正常工作? 他們之間有什麼不同?

+8

NG-重複會爲每個元素的新範圍,當你在你的第二個例子做'selectedRow = $ index',它的工作原理,但只有上線的電流範圍,而不是在你需要它的父範圍,更明確地,你可以做'$ parent.selectedRow = $ index'這將工作,但不是真正的優化看着它,最好的辦法這裏是你的第一個 – DotDotDot

+0

你已經選擇行控制器predfined?林不記得是這種情況下需要這種 – makallio85

+0

DotDotDot是正確的! – makallio85

回答

0

ng-click='selectRow($index)'會調用一個名爲selsectRow()函數,並將它傳遞的行的索引。

ng-class="{select:$index == selectedRow}該表達式將基於布爾運算$index == selectedRow的結果更改此指令的類的名稱。