AngularJS: choosing just one option from a group of checkboxes

Is there a way to implement single selection on checkboxes, similar to an HTML "select" element?

I currently have a basic HTML table structure:

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

In addition, I have defined some simple controller functions for these directives:

$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;
    }
};

However, it seems that the current implementation is not functioning as expected. Upon investigation, I discovered that ng-click has a priority of 0 compared to ng-checked with a priority of 100.

Are there any elegant solutions available to solve this issue?

Answer №1

To connect ng-model with subscription.checked, and use ng-click to uncheck all other subscriptions except the one that is clicked. This will allow for toggling of checkboxes.

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

Instead of a regular for loop, you can utilize angular's forEach which provides better readability by aliasing each item as subscription:

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

For a live demonstration, visit: http://plnkr.co/edit/XD7r6PoTWpI4cBjdIZtv?p=preview

Answer №2

<!DOCTYPE html>
<html>

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script>
    angular.module('app', []).controller('appc', ['$scope',
      function($scope) {
        $scope.selected = 'other';
      }
    ]);
  </script>
</head>

<body ng-app="app" ng-controller="appc">
  <label>SELECTED: {{selected}}</label>
  <div>
    <input type="checkbox" ng-checked="selected=='male'" ng-true-value="'male'" ng-model="selected">Male
    <br>
    <input type="checkbox" ng-checked="selected=='female'" ng-true-value="'female'" ng-model="selected">Female
    <br>
    <input type="checkbox" ng-checked="selected=='other'" ng-true-value="'other'" ng-model="selected">Other
  </div>



</body>

</html>

Answer №3

In order to achieve a similar functionality, I implemented the following code snippet. The key is utilizing the ng-click attribute which works seamlessly. Both checkbox-1 and checkbox-2 are boolean values.

<form>
    <input type="checkbox" ng-click="checkbox-2 = false" ng-model="checkbox-1">
    <input type="checkbox" ng-click="checkbox-1 = false" ng-model="checkbox-2">
</form>

Answer №4

If you're looking for a solution, here are three recommendations that come to mind:

  1. Consider creating a directive that automates the setup of checkboxes and manages their state internally. However, this approach may not be optimal as it shifts a model rule (only one subscription checked) into a DOM manipulation challenge.
  2. Another option is to structure your model in a way that ensures only one subscription can be active at a time. Keep in mind that modifying the model during a change event can trigger additional digest cycles, which could lead to unwanted outcomes.
  3. Alternatively, you could switch to using radio buttons instead of checkboxes. This will enforce the single selection requirement more effectively.

Personally, I lean towards option 3 as I prefer leveraging native input elements whenever possible.

<tr ng-repeat="subscription in entities">
<td><input type="radio"
   ng-model="selection"
   name="subscriptionRadio"
   value="{{subscription}}"/>
</td> 
</tr>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How does an arrow function access parameters even when they have not been explicitly passed in?

The PhotosPage component is being rendered with the following route: <Route path="/settings/photos" component={PhotosPage} /> The component's signature includes: const PhotosPage = ({ uploadProfileImage, photos, profile, deletePhoto, ...

How to validate a <select> element with parsley.js when it is dynamically populated with an object?

I'm struggling to validate a <select> element in my form. With the help of knockout.js, I select a location which then populates the Service Point based on the Location chosen. However, when I try to validate the form using parsley.js after pres ...

Refresh your webpage with new content and modified URLs without the need to reload using window.history.pushState

Hey everyone, I'm looking to incorporate window.history.pushState into my website, but I'm unsure of how to go about it... What I'm aiming for is to have a page dashboard.php and update the URL to dashboard.php?do=edit&who=me, while loa ...

"Enhance the functionality of multiple elements with this innovative Jquery

Exploring the realm of Jquery plugins, I am faced with the challenge of making my plugin compatible with multiple elements. After scouring tutorials and various online forums, I've come to realize that plugin development is heavily dependent on the sp ...

What is the purpose of form.$valid verifying the validity of non-required fields?

I am facing an issue with my AngularJS form. I have a few required fields and one field that is not required. My goal is to only consider the required fields when checking if the form is valid. However, whenever I use form.$valid, it always returns false u ...

AngularJS directive created for validation on blur

I am striving to replicate some of the features found in Angular 1.3.X for the app I am developing, with a particular focus on ensuring compatibility with IE 8. Unfortunately, this constraint means that I cannot utilize version 1.3.X. I have encountered di ...

Ways to implement debounce in handling onChange events for input fields in React

I've been attempting to implement debounce functionality in my React app without relying on external libraries like lodash or third-party node modules. I've tried various solutions found online, but none have worked for me. Essentially, in the h ...

`odd communication between Node.js and Neo4j`

While working on a simple application with Neo4j and Node.js, I encountered an issue that has left me puzzled. I am able to insert data into Neo4j successfully, but when I try to retrieve additional node attributes using Cypher, I receive the following err ...

Encountered an issue while attempting to retrieve the access token from Azure using JavaScript, as the response data could

Seeking an Access token for my registered application on Azure, I decided to write some code to interact with the REST API. Here is the code snippet: <html> <head> <title>Test</title> <script src="https://ajax.google ...

Angular-Material - Issue related to Theme Implementation

Recently, I discovered Angular-Material. However, it appears that the theme files are not automatically included by the base angular-material.css file. As a result, I have to manually include each color theme that I want to use... If anyone has dealt wit ...

Comparing AngularJS and AppML

As a beginner in AngularJS and AppML, I am curious to understand the strengths and differences between these two frameworks. Despite some similarities I noticed on W3Schools, I'm eager to dive deeper into each one's unique features. ...

How to Use Google Tag Manager to Track Forms with Various Choices

Currently, I am facing a challenge in setting up conversion tracking using GTM for a form that offers users multiple options via a drop-down menu. When the user clicks on an option, they are presented with choices like A, B, C, and D. After selecting an ...

Babylon entities failing to run

Encountering a strange issue in my current project. I am working on a react application that incorporates Babylonjs for 3D rendering. While I am able to successfully load objects into the scene, I am facing a problem when attempting to create a PBR Materia ...

AngularJS is unable to find the controller specified

Whenever I attempt to launch my application, I encounter this particular error. An issue arises where 'CampaignsSettingsController' is not recognized as a function and is instead undefined. The controller in question is outlined below: // Exec ...

What is the best way to create a test for my Vue component using Jest?

Below is the login form component that needs to be tested for various scenarios: Verify successful login with both username and password filled Check for input error when either username or password is left blank Ensure input error is thrown when only us ...

How can I parse JSON in React using the Parse function?

I am currently working with three list components, and when I click on any item in the tree list, it displays the JSON data. However, I would prefer to view it in a parse format rather than JSON. I attempted to use let json = JSON.parse(this.props.node, n ...

Using ThreeJs to create interactive 3D objects with button-controlled movement

Currently, I'm diving into the world of Three.js and I have a fascinating project in mind. I want to create movement buttons that will control the position of a sphere object. Through some research, I found out that I can use the onclick function on b ...

Notifying with Socket.IO in Node.js

Hey there, I'm currently working on implementing a notification system but have hit a roadblock. I've sent an invitation to a user to join the club. socket.on("notify", async (message) => { // invite the user John Doe io.to('socke ...

Using TypeGraphQL with Apollo Server for File Uploads

What I'm Striving to Achieve I am attempting to implement file uploads using typegraphql (a wrapper on Apollo Server). I have created a basic resolver that is supposed to receive a file upload and save it to the server. The Code I'm Using This ...

The functionality of grunt-contrib-copy is causing irreversible damage to binary files

My current setup involves using the "grunt-contrib-copy": "^1.0.0" library, but I'm facing an issue where the binary files that are copied end up getting damaged. Could someone please take a look at my grunt configuration and provide assistance in res ...