angularjshtml-tableangular-ui-bootstrapsmart-table

AngularJs - allow only one item to be selected in Table


I am using smart table. I have a logic behind where I only need one item to be selected. My current table code allow multiple lines to be selected.

enter image description here

This is my HTML:

 <table st-safe-src="flow3.dataSet" st-table="flow3.displayed" class="table table-striped">

                <thead>
                <tr>
                    <th st-sort="method">Method</th>
                    <th st-sort="sample">Sample</th>
                    <th st-sort="parameters">Parameters</th>
                </tr>
                </thead>
                <tbody ui-sortable ng-model="flow3.displayed">
                <tr ng-repeat="row in flow3.displayed track by $index" style="cursor: move;" ng-click="row.selected = !row.selected; flow3.selectRow($event, row)" ng-class="{success: row.selected}">
                    <td>{{row.method.name}}</td>
                    <td>{{row.sample}}</td>
                    <td>
                        <span ng-repeat="parameter in row.parameters">{{parameter.methodInputParameter.name}} : {{parameter.value}}<br/></span>
                    </td>
                    <td>
                        <button type="button" ng-click="flow3.removeItem(row)"
                                class="btn btn-danger btn-sm btn-round pull-right"
                                ng-disabled="flow3.confirmDisabled">
                            <i class="glyphicon glyphicon-trash"></i>
                        </button>
                    </td>
                </tr>
                </tbody>
</table>

This is my JS:

 flow3.selectRow = function($event, row) {
        flow3.selectedItem = row; 
}

Solution

  • If you want the only one row with selected property set to true, you should modify your selectRow method to accept the collection of all rows and then de-select all before selecting clicked one:

    flow3.selectRow = function($event, row, rows) {
      //de-select all
      angular.forEach(rows, function(r){ r.selected = false; });
      //select clicked
      row.selected = true;
      flow3.selectedItem = row; 
    }
    ng-click="flow3.selectRow($event, row, flow3.dataSet)"

    If you want to apply different css class to the clicked/selected item you probably can leave your selectRow method as is (since we have the selected item as flow3.selectedItem) and change the condition in the ngClass directive to be (if rows have some unique id property for example):

    ng-class="{success: row.id === flow3.selectedItem.id}"

    Hope this helps.