Toggling checkboxes using Angular framework

Within my form, there is a table with checkboxes in each column. The table consists of 3 <tr> elements, and each <tr> uses ng-repeate to call the webservice and display clone data (in JSON format). Upon clicking a checkbox, I create a JavaScript array to store the IDs using the following function :

checkoptions(array, model) {
angular.forEach(array, (value, key) => {
  if (array[key].checked) {
    model.push(array[key].id)
  }
})

Regarding the HTML structure :

<tr ng-repeat="developer in $ctrl.developers">
    <td>{{developer.label}}</td>
    <td>
      <input type="checkbox" id="{{developer.id}}"
          ng-change="$ctrl.checkoptions($ctrl.developers,$ctrl.employees.developers)" 
             ng-model="developer.checked">
                <label for="{{developer.id}}"></label>
     </td>

The functionality works as intended, but the issue arises when unchecking a checkbox - it remains in the JavaScript array.

Answer №1

I made a modification to the code by adding an else statement to remove items from the array: http://jsfiddle.net/x9m1nqvp/1/

      $scope.checkoptions = function (array, model) {
        angular.forEach(array, (value, key) => {
          if (array[key].checked) {
            var index = model.indexOf(array[key].id);
            if(index == -1)
                model.push(array[key].id)
          }
          else {
            var index = model.indexOf(array[key].id);
            if(index >=0)
                model.splice(index, 1);
          }
      })

Answer №2

Although Everton's solution accomplishes the task, it can be seen as overly repetitive to iterate through every item in the array whenever a single checkbox changes state. There is no need to update each individual item in the array when only one checkbox is being toggled.

The following code snippet provides an alternative approach where only the specific checkbox that is toggled will be added to or removed from the employees.developers array (Note: eliminating the necessity of using angular.forEach):

$scope.checkoption = function (developer) {
    if (developer.checked) {
        var index = $scope.employees.developers.indexOf(developer.id);
        if (index == -1)
            $scope.employees.developers.push(developer.id)
    } else {
        var index = $scope.employees.developers.indexOf(developer.id);
        if (index >= 0)
            $scope.employees.developers.splice(index, 1);
    }
}

You can implement this logic in your HTML template like so:

<tr ng-repeat="developer in developers">
    <td>{{developer.label}}</td>
    <td>
        <input type="checkbox" id="{{developer.id}}"
            ng-change="checkoption(developer)" 
            ng-model="developer.checked">
        <label for="{{developer.id}}"></label>
    </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

What is the correct way to establish a Cookie (header) using XMLHttpRequest in JavaScript?

I am attempting to set a cookie in an XSS request using XMLHttpRequest. After reviewing the XMLHttpRequest Specification, I discovered that section 4.6.2-5 indicates that setting certain headers like Cookie and Cookie2 may not be allowed. However, I am lo ...

The size of the search input and textarea in HTML decreases when viewed on an iPad device

Currently utilizing Bootstrap 3 and AngularJs for this project. Implementing the following markup for the input field with type 'search': <input type="search" class="form-control" id='roomSearch' placeholder="Search" ng-model=&apo ...

Could one harness the power of SO's script for adding color to code within questions?

Similar Question: Syntax highlighting code with Javascript I've observed that Stack Overflow utilizes a script to apply color coding to any code shared in questions and answers, making it resemble how it would appear in an IDE. Is this script pub ...

Vanishing Items - Three.js CanvasRenderer

I'm in a bit of a pickle here. I can't figure out why my objects are disappearing when using the canvas renderer. Strangely enough, everything works fine with the webGL renderer. Unfortunately, I need to make sure this displays properly on mobile ...

What are the ways to enable VS Code's Intellisense to collaborate with AngularJS's injected services?

Hey, I've been trying to get Visual Studio Code to provide me with its intellisense for my unique framework (not Angular) app's services. Although I managed to get the standard type for such frameworks, I'm struggling to find a solution for ...

Steps to combine multiple arrays into a unified array:1. Begin by allocating a

To form a league table, I have multiple individual arrays filled with data. In order to sort them by points, I want to merge these arrays into a single array called "teams". However, I am unsure if there is a function available to achieve this specific f ...

What is the best way to include a new array at the beginning of a lexicographically sorted array?

After lexicographically sorting an array, I am trying to figure out how to add values from another array "cityOfTheMoscow" first and then maintain the lexigraphical order. However, while using the code snippet below: result.unshift(...self.cityOfTheMoscow ...

JavaScript resets the timer whenever the page is refreshed

Is there a way to maintain the timer in a quiz even after refreshing the page? <html><h1>Js Timer</h1> <div style="font-weight: bold;" id="quiz-time-left"></div> <script type="text/javascript"> var total_seconds = ...

Transforming a date into a name: tips and tricks

I've encountered an issue with the code below. I am trying to convert the months to names like "October", "November", and "December" using MONTHNAME. However, whenever I attempt this, I run into an error similar to the following: "JulyError in quer ...

how to make a post request to an API using Next.js

I am attempting to make a request to the Exist API using next.js and the backend is in PHP. I am trying to send a post request (using Axios) with data and retrieve the response. How can I manage this API in my code? I have read that I need to include som ...

generating a new array object during every iteration

I have encountered an issue while attempting to create a ddData object for each element with the id #user. The problem is that only the last object is being displayed. Below is the JavaScript code I am using: var count = $('*#user').length; ddD ...

Having trouble getting your AngularJS code to work?

Recently, I decided to experiment with AngularJS and started working on a new project. Below is the HTML code I wrote: <div ng-app ng-controller="nameController"> <input type="text" value="Jack" ng-model="fname" /> <input type="tex ...

Sending AngularJS $http.post JSON request to an ExpressJS server, eagerly awaiting response

I'm encountering an issue with pending $http.post requests from AngularJS to Express when attempting to post to MongoDB. Here is my app.js configuration: app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.static(__d ...

What is the best way to substitute unpredictable dynamic variables on-the-fly?

I am working with a .js file that contains a config structure similar to this: genGetLocations:{ data_url:'restaurants/{var1}/tables/{var2}, } This is just one example. Some configurations may have data_url with more than two dynamic variables. I ...

Include a <div> element to display the date in an HTML format, ensuring that the days and months

I am working on a project where I have a list of dates and I need to format them by adding div tags to separate the days, months, and years into different divisions. <div class="campaign">30/11/2016 - <a href="#" target="_blank">Dummy Text& ...

Encountered a "Transformer is not a constructor" error when trying to upgrade the React Native SDK version from 0.61.5 to 0.64

https://i.sstatic.net/LYdxj.pngRecently, I upgraded my react native version to the latest one and encountered an error stating "Transformer is not a constructor". The metro-react-native-babel-preset version I am currently using is 0.64.0. Can someone ple ...

Is there a way to confirm if all div elements have a designated background color?

I have a scenario where I have dynamically added several divs with a specific class to my webpage. These divs change color when the user hovers over them. I am trying to trigger a specific function once the last div has been set to a particular backgroun ...

The proper way to compare numbers in JavaScript

I need to determine the color for my legend by comparing two values without using ceil, floor, or round functions. The color is based on a color table with point and RGB values. The backend provides points like 0.4607441262895224, 0.5500956769649571, etc. ...

ng-click fails to trigger after being added following the completion of the page load

I'm attempting to perform a variable replacement while also making it clickable using ngClick. I created a plunker demonstration (click the button and notice that the input box remains unchanged) Structure: <body ng-controller="Ctrl"> <i ...

Ways to retrieve property value from a component in Vue.js 2.0

I am currently working with a specific component that allows for date selection: <template> <div class="animated fadeIn"> <div class="col-sm-6 col-lg-6"> <datepicker class="form-control" :value="config.state.fromDate" ...