15

I have got a table, styled with bootstrap. The content of this table is filled using Angular.js. How do I make a row clickable so it will call a function in the scope?

The following code does not work for me (the ng-click part):

Table:

    <table class="table table-hover">
        <thead>
            <tr>
                <th>Name</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="ingredient in ingredients" ng-click="setSelected({{$index}});">
                <td>{{ ingredient.name }}</td>
                <td>{{ ingredient.status }}</td>
            </tr>
        </tbody>
    </table>

Controller:

$scope.setSelected = function(index) {
    $scope.selected = $scope.ingredients[index];
    console.log($scope.selected);
};
Klaasvaak
  • 5,634
  • 15
  • 45
  • 68
  • 2
    I think you just need to remove the {{}} around $index but you should describe better how it fails. For example you show that you're logging it but not the output of the log. – shaunhusain Jul 15 '13 at 15:55
  • Nothing happens, no logging. But the {{$index}} is rendered to an numeric value. – Klaasvaak Jul 15 '13 at 16:23

4 Answers4

43

Suggestion and the fiddle:

<tr ng-repeat="ingredient in ingredients" ng-click="setSelected();">
    <td>{{ ingredient.name }}</td>
    <td>{{ ingredient.status }}</td>
</tr>

<script>
var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {

    $scope.ingredients = [
        {'name': 'potato'},
        {'name': 'tomato'}
    ];

    $scope.setSelected = function() {
        $scope.selected = this.ingredient;
        console.log($scope.selected);
    };

}
</script>
marko
  • 2,841
  • 31
  • 37
  • 10
    To decouple controller and template you can use `ng-click="setSelected(ingredient);"` and `$scope.setSelected = function(item) { ... };`. – Eugene Jul 15 '14 at 08:12
2

You could just pass the ingredient in argument

ng-click="setSelected(ingredient)"

and in controller

   $scope.setSelected = function(my_ingredient) {
       $scope.selected = my_ingredient;
       console.log($scope.selected);
   };
Parth Acharya
  • 545
  • 3
  • 13
1

HTML:

<table class="table-hover">

CSS:

.table-hover > tbody > tr:hover {
    background-color: #f5f5f5;
}

And if also whats made the tr selectable:

HTML:

<tr ng-click="doSomething()">

CSS:

tr[ng-click] {
    cursor: pointer;
}

View JSFiddle Sample

pdorgambide
  • 1,787
  • 19
  • 33
0

Angular 6

HTML:

<tr (click)="doSomething()">

CSS:

tr:hover {
    cursor: pointer;
}
Stefan Mitic
  • 1,551
  • 1
  • 8
  • 8