2014-10-16 51 views
0

我正在從O'REALLY閱讀AngularJS書。而在第28頁,它說,我們可以設置從模板的模型:設置模型和ng級的行爲

由於表達式執行與他們的元素相關聯的控制器的範圍的情況下,表達式設定的屬性是一樣的設置屬性控制器的範圍。

並且作爲示例示出:

<button ng-click='count=3'>... 
has the same effect as: 
<button ng-click='setCount()'>... 
where function 
CountController($scope) { $scope.setCount = function() {$scope.count=3; }} 

所以,我試圖執行以下操作:

<!DOCTYPE html> 
<html ng-app = 'restaurantApp'> 
<body> 
<table ng-controller="restaurantTableController"> 
    <tr ng-repeat= 'restaurant in directory' 
     ng-click = 'selectedRow = $index' 
     ng-class = '{selected: $index == selectedRow}'> 
     <td>{{restaurant.name}}</td> 
     <td>{{restaurant.cuisine}}</td> 
    </tr> 
</table> 
<style> 
    .selected{ 
     background-color: lightgreen; 
    } 
</style> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script> 
<script> 
    var restaurantModule = angular.module('restaurantApp',[]); 
    restaurantModule.controller('restaurantTableController', function ($scope) { 
     $scope.selectedRow = null; 
     $scope.directory = [{name: 'cevichesa', cuisine: 'seafood'}, 
      {name: 'arnoldos', cuisine: 'pizza'}]; 
     $scope.selectRestaurant = function(row){ 
      $scope.selectedRow = row; 
     }; 
    }); 
</script> 
</body> 
</html> 

ng-click = 'selectedRow = $index'就是我設立從視圖的模塊。 但行爲是點擊的行變綠並在選擇其他行後保持綠色。

另一方面,如果我將此行替換爲ng-click = 'selectRestaurant($index)',則行爲與預期的一樣,即單擊的行在單擊其他行時變綠並淡入。

我不知道發生了什麼。歡迎任何解釋。我會說改變selectedRow的兩種方式應該可以正常工作。但顯然我錯過了一些東西。

謝謝你的幫助。

回答

0

這是因爲ng-repeat創建自己的子範圍,所以如果你有重複之內:

ng-click = 'selectedRow = $index' 

它集子範圍selectedRow - 獨自離開父母。現在,如果你調用該函數:

ng-click = 'selectRestaurant($index)' 
$scope.selectRestaurant = function(row){ 
    $scope.selectedRow = row; 
}; 

這是指selectedRow父範圍 - 因此沒有允許選擇超過1行。

+0

感謝您的回答。所以'ng-class ='{selected:$ index == selectedRow}''正在尋找像一連串範圍內的selectedRow,其中ng-repeat的範圍在開頭。 – 2014-10-16 15:20:45

+1

如果'ng-class'在中繼器內,它將首先檢查'selectedRow'的當前範圍(當前迭代範圍) - 如果找不到,它將查找鏈。 – tymeJV 2014-10-16 15:21:53