3

I have a simple table in an Angularjs app that contains a checkbox in each row.

<table>
    <tr ng-repeat="obj in objList">
        <td>
            <input type="checkbox" ng-model="selectedObjs" value="{{obj}}"
                         ng-checked="obj.selected" 
                         ng-click="toggleObjSelection(obj.description)">
                {{obj.description}}
            </input>
        </td>
    </tr>
</table>

Is there a way in Angularjs to allow the user to click any where within the row to trigger the checkbox click once?

If the user clicks in the checkbox, we don't want to trigger the click so that it appears that the checkbox click was triggered twice.

This article (http://www.learningjquery.com/2008/12/quick-tip-click-table-row-to-trigger-a-checkbox-click/) describes how to do this in jQuery, but is there a way to do this using Angularjs style?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Delvin Defoe
  • 91
  • 1
  • 1
  • 6

1 Answers1

14

You're pretty close you just need to stopPropagation on the $event object:

<table ng-controller="ctrl">
<tr ng-click="rowClicked(obj)" ng-repeat="obj in objList">
    <td>
        <input type="checkbox" ng-model="selectedObjs" value="{{obj}}"
                     ng-checked="obj.selected" 
                     ng-click="toggleObjSelection($event, obj.description)">
            {{obj.description}}
        </input>
    </td>
</tr>
</table>

And the JS:

angular.module('myApp', [])
   .controller('ctrl', function($scope) {
   $scope.objList = [{
       description: 'a'
   },{
       description: 'b'
   },{
       description: 'c'
   },{
       description: 'd'
   }];

   $scope.toggleObjSelection = function($event, description) {
        $event.stopPropagation();
       console.log('checkbox clicked');
   }

   $scope.rowClicked = function(obj) {
       console.log('row clicked');
       obj.selected = !obj.selected;
   };
});

http://jsfiddle.net/Ljwv0toh/7/

Related question: AngularJS ng-click stopPropagation

Community
  • 1
  • 1
Daniel
  • 423
  • 5
  • 11
  • This worked perfectly, except in function `$scope.rowClicked()` I changed `obj.selected = true;` to `obj.selected = !obj.selected;`. – Delvin Defoe Sep 18 '14 at 14:58
  • Glad it worked and I approved your edit -- makes sense. Could you accept the answer? – Daniel Sep 18 '14 at 15:10