Utilizing AngularJS to implement checkbox selection within a table

I'm working on a method that will receive an Id from a table when a checkbox is checked and update the $scope.selected array in my Angular controller. If the checkbox is unchecked, it should remove the corresponding item from $scope.selected.

Here's what I have so far:

$scope.updateselection = function(id) {
   if ($scope.selected(sort_id) != id) { //not sure about the syntax here??
       $scope.selected.push({ sort_id: id });
   } else {
       $scope.selected.remove({ sort_id: id });
   }
};

Answer №1

If you're looking to handle checkbox interactions in Angular, I highly recommend using the directive provided at

Alternatively, if you prefer not to use this directive, you can set up a watcher for your checkboxes table.

Here's an example:

HTML:

<table>
    <tr>
        <td ng-repeat="item in items">
            <input type="checkbox" ng-model="item.value"> 
        </td>
    </tr>
<table>

JS:

 $scope.items = [
        {
            name: "name1",
            value: true
        },
        {
            name: "name2",
            value: false 
        }
    ];

    $scope.selectedItems = [];

    $scope.$watch('items', function(newValues){
        $scope.selectedItems.length = 0;
        angular.forEach(newValues, function(item) {
            if (item.value == true) {
                $scope.selectedItems.push(item.name);
            }
        });
        console.log($scope.selectedItems);
    }, true);

This approach ensures that you always have up-to-date information regarding the selected checkboxes.

I've even put together a JSFiddle with a live demo for your convenience.

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

The one-time binding notation does not seem to be functioning as expected in AngularJS version 1.6.4

For our application, we are utilizing AngularJS 1.6.4 to display a large number of rows on a single page. However, when it reaches around 7K entries, the page starts hanging. To tackle this issue, we have opted for one-time binding for those specific pages ...

Securing your Angular application with user authentication and route guarding ensures

In the process of developing an Angular single-page application (SPA) front-end that interacts with a GraphQL endpoint, I encountered a challenge. Upon user login, I store the token in local storage and update the authentication state in my AuthService com ...

Utilizing setState within the useEffect hook can lead to the application experiencing

Why does my code result in an endless loop error? This issue is pointing to the line marked with *: function Blog() { const [blog, setBlog] = useState({}); const query = useQuery(); async function fetchBlog(query) { const data = awai ...

Leveraging JSON for parsing xmlhttp.responseText to auto-fill input fields

Is there a way to utilize JSON for parsing xmlhttp.responseText in order to populate textboxes? I've been struggling to achieve this using .value and .innerHTML with the dot notation, along with b.first and b.second from the json_encode function in th ...

Reposition the element at the bottom of its parent element

I am facing an issue with the HTML structure in my application: <div class="work-item"> <div class="image-container"> </div> <div class="text-container"> </div> </div ...

What is the most compatible JavaScript framework for openlayers?

I'm seeking guidance on selecting a front-end framework (e.g. React, Vue, Angular) that is compatible with OpenLayers for my upcoming implementation. Could you please recommend the most suitable front-end framework to work seamlessly with OpenLayers? ...

What's the best way in Angular 6 to set focus on an element that's being made content editable?

I am currently utilizing the contentEditable attribute in Angular 6 to allow for editing the content of elements within an ngFor loop. Is there a way to focus on a tag element when its contentEditable attribute is set to true? <div class="tag" *ngFor= ...

Utilizing the props value for emission within the emits array: A guide

While attempting to list a custom event in the component's emits option, I encountered a console error. The code looked like this: PARENT <Btn event-name="toggleSideMenu" @toggle-side-menu="toggleHandler"> togg ...

Is it possible to utilize AJAX to load the URL and then extract and analyze the data rather than

I had originally created a web scraping method using PHP, but then discovered that the platform I was developing on (iOS via phone gap) did not support PHP. Fortunately, I was able to find a solution using JS. $(document).ready(function(){ var container ...

How can you make an Angular directive activate only after the scope function in an ng-click handler has been executed?

Scenario I am relatively new to Angular and facing a specific challenge. The goal is to make a directive change the color and add an image to a button. However, I am struggling to get the first if condition to work in my Angular Directive. Issue The ob ...

Attempting to utilize the Optimist API's help() function to display the usage() information

I am relatively new to using optimist and despite my attempts at researching and experimenting, I have been unable to find a streamlined method for incorporating a --help option. In the documentation, there is mention of a help() function. Based on this i ...

Discovering the identification of a comment in JavaScript

Here is the code snippet I am working with: <a onclick="lel($(this),'212345555')" class="button"> <a onclick="lel($(this),'241214370')" class="button"> <a onclick="lel($(this),'248916550')" class="button"> & ...

How to transform a Dictionary containing lists of objects into JSON using C#

In my database, I have two tables with a one-to-many relationship. States have many cities. I retrieve this data from the database and convert their relationships into objects using C# logic. I need to convert Dictionary<State, List<City>> to ...

Why is my AngularJS controller receiving 'undefined' data from my service request?

Question: I am facing an issue where my service is successfully retrieving the necessary data, but my controller is not able to access it. What could be causing this problem? Service: Below is the code that my controller calls. // search.service.js (func ...

What is the best way to parse this JSON data?

Here is a string that I have: [{"data1":"A"},{"data2":"B"},{"data3":"C"}] Using jQuery, I converted this string to JSON: test_json = $.parseJSON('[{"data1":"A"},{"data2":"B"},{"data3":"C"}]'); After conversion, I obtained 3 objects: https:/ ...

Convert a string with the characters '"' retrieved from a MySQL database into JSON

After creating a JSON object and storing it in MySQL, I encountered an issue when trying to retrieve and parse it. When I stringify the JSON object, the properties are being enclosed in double quotes causing issues when parsing the retrieved string. Below ...

Adjusting the dimensions of a table

I've been utilizing jQuery datatable and I am facing a challenge where the table width extends beyond the container it should be contained in. I've attempted several solutions to fix this issue: 1. Setting the sWidth option on both the table an ...

Issue with installing vscode-ripgrep during VSCode build/run process

After attempting to build and run VSCode on my Ubuntu 17.10 by following the instructions from this guide: https://github.com/Microsoft/vscode/wiki/How-to-Contribute#build-and-run, I encountered an issue when installing dependencies using yarn. The error m ...

Setting a default image for the img setAttribute: A step-by-step guide

My code involves creating an img element using JavaScript: var photo = document.createElement("img"); This element is populated with photos whose names are stored in an array of objects. The images are loaded like this: photo.setAttribute('src&apos ...

Webix UI - Struggling to create dynamically responsive components during screen resizing

Can anyone guide me on how to make my Webix UI control responsive in the free version available at ? It seems to be acting unpredictably due to the AngularJS integration code I'm using. I have attempted various solutions like media queries, redraw, a ...