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?

1
  • You can use delegate Commented Sep 17, 2014 at 21:21

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

This worked perfectly, except in function $scope.rowClicked() I changed obj.selected = true; to obj.selected = !obj.selected;.
Glad it worked and I approved your edit -- makes sense. Could you accept the answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.