I recently had this problem where I had to select an item from a table. Nothing much, but I avoided buttons for this task and instead used a radio button against each row:
where
$scope.users = [{“userId”: 1, “firstName”: “a”,“lastName”:“b”},
{“userId”: 2, “firstName”: “c”,“lastName”:“d”},
{“userId”: 3, “firstName”: “e”,“lastName”:“f”}];
and
$scope.toggleSelection = function (index) {
$scope.selectedUsers = $scope.users[index];
};
I used $scope.selectedUsers to retain the selected object. In operation this worked fine in the context that whatever item was selected last would be retained except that on clicking one radio button after another the previous radio button was not getting cleared. The problem here being that ng-repeat creates a new child scope from the parent scope of the table for each new row. I searched around and came across instances that pointed that I need to be using $parent.user as my ngModel instead of just user. Instead of resorting to such deliberate methods, here is what I did:
In the controller, I added a new attribute to each item in the users array:
for(var i = 0; i < $scope.users.length; i++){
$scope.users[i].selectedValue = false;
}
and in the toggleSelection function, I reset the selectedValue again:
$scope.toggleSelection = function (index) {
$scope.selectedUsers = $scope.users[index];
for(var i = 0; i < $scope.users.length; i++){
$scope.users[i].selectedValue = false;
}
};
In the DOM:
And now all the radio buttons are cleared on clicking by the ng-value attribute in the DOM but as soon as the click event is completed ng-dirty class is automatically applied to the radio button on which the click was applied and this fills the selected radio button.