【问题标题】:Click Table Row to Trigger a Checkbox Click in Angularjs单击表格行以触发 Angularjs 中的复选框单击
【发布时间】:2014-11-12 01:35:16
【问题描述】:

我在 Angularjs 应用程序中有一个简单的表格,每行都包含一个复选框。

<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>

Angularjs 中有没有办法允许用户单击行中的任何位置来触发复选框单击一次?

如果用户点击复选框,我们不想触发点击,这样看起来复选框点击被触发了两次。

这篇文章 (http://www.learningjquery.com/2008/12/quick-tip-click-table-row-to-trigger-a-checkbox-click/) 描述了如何在 jQuery 中做到这一点,但是有没有办法使用 Angularjs 风格做到这一点?

【问题讨论】:

  • 你可以使用委托

标签: angularjs checkbox triggers html-table row


【解决方案1】:

你已经很接近了,你只需要在 $event 对象上停止传播:

<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>

还有 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/

相关问题:AngularJS ng-click stopPropagation

【讨论】:

  • 这很好用,除了函数 $scope.rowClicked() 我将 obj.selected = true; 更改为 obj.selected = !obj.selected;
  • 很高兴它成功了,我批准了你的编辑——说得通。你能接受答案吗?
猜你喜欢
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-07
相关资源
最近更新 更多