Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
7
rated 0 times [  13] [ 6]  / answers: 1 / hits: 44749  / 10 Years ago, thu, april 24, 2014, 12:00:00

I am trying to force a single-selection on checkboxes, similar to a html select



I have a html simple table:



<tr ng-repeat=subscription in entities>
<td>
<input type=checkbox ng-checked=isChecked(subscription) ng-click=toggleSelection(subscription)/>
</td>
</tr>


Then I have some simple controller functions for those directives above:



$scope.isChecked = function(entity) {
return $scope.checkedEntity === entity;
};

$scope.toggleSelection = function(entity) {
entity.checked = !entity.checked;
if (entity.checked) {
$scope.checkedEntity = entity;
} else {
$scope.checkedEntity = null;
}
};


Unfortunately it doesn't work, and I think I just discovered why.... the ng-click has 0 priority, vs 100 for ng-checked.



Is there an elegant solution for this problem?


More From » angularjs

 Answers
4

Bind ng-model to subscription.checked, and have ng-click uncheck all subscriptions except the one clicked. Since these are checkboxes, the one clicked will toggle itself.



<tr ng-repeat=subscription in entities>
<td>
<input ng-model=subscription.checked ng-click=updateSelection($index, entities) type=checkbox />
</td>
</tr>


You can use a plain for loop, but angular's forEach allows us to alias each item as subscription and improve readability:



$scope.updateSelection = function(position, entities) {
angular.forEach(entities, function(subscription, index) {
if (position != index)
subscription.checked = false;
});
}


Here is a working demo: http://plnkr.co/edit/XD7r6PoTWpI4cBjdIZtv?p=preview


[#71307] Wednesday, April 23, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jerome

Total Points: 592
Total Questions: 98
Total Answers: 101

Location: Tonga
Member since Tue, Nov 30, 2021
3 Years ago
jerome questions
Thu, Jan 27, 22, 00:00, 2 Years ago
Fri, Oct 22, 21, 00:00, 3 Years ago
Sat, Sep 19, 20, 00:00, 4 Years ago
Fri, Sep 6, 19, 00:00, 5 Years ago
;