设置模型和ng-class的行为

时间:2014-10-16 15:05:21

标签: angularjs

我正在阅读O'真正的AngularJS书。在第28页,它说我们可以从模板中设置模型:

  

由于表达式在与其元素关联的控制器范围的上下文中执行,因此在表达式中设置属性与设置控制器范围的属性相同。

并举例说明:

<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的两种方式应该可以正常工作。但显然我错过了一些东西。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这是因为ng-repeat创建了自己的子范围,所以在重复范围内如果你有:

ng-click = 'selectedRow = $index'

设置子范围selectedRow - 并让父母单独留下。现在,如果你调用函数:

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

这是指父范围中的selectedRow - 因此不允许选择超过1行。