What is the best way to capture all the selected values and send them to an Angular controller?

Recently, I've been working on adding a bulk post delete feature to my system. The idea is to have a list of posts with checkboxes next to each one, and when a user clicks a button, the selected posts should be deleted.

My approach involves assigning each post's id as the value for the checkbox, then passing all the checked values to an Angular controller. From there, the backend can use these ids to search for the corresponding posts and delete them.

Despite my efforts, I'm struggling to figure out how to pass all those values effectively.

Here is a snippet of what I have so far:

<td><input type="checkbox" value="post.id" name="posts"></td>

<button class="btn btn-info pull-middle" ng-show="showDelBtnAndTableHeaders" ng-click="destroySelected(selectedPosts)">Delete Selected Posts</button>

I've also included this function in the controller, but I haven't been able to successfully retrieve the array of values for deletion despite several attempts:

    $scope.destroySelected = function (array) {
        console.log(array);
        Post.destroySelected(array)
            .success(function () {

            })

    };

If anyone has any insights or suggestions on how to improve this process, I would greatly appreciate it. Thank you!

Answer №1

It seems that the correct code to use here is: value="post.id"

Do not use: value="selectdPosts.id"

Also, make sure to replace:

ng-click="destroySelected(selectedPosts)"

with: ng-click="destroySelected(post)"

Answer №2

Feel free to view the Plunker link provided in the comments section since I am unsure how to attach it here. I successfully used a filter to retrieve all selected IDs and accessed them upon button click. You can now utilize this information for your post call.

Answer №3

Here is a straightforward solution to solve your issue:

See the solution in action on JSFiddle

HTML Code:

<div ng-controller="PostController">
<label ng-repeat="post in posts">
<input type="checkbox" name="selectedPosts[]" value="{{post.id}}"ng-model="post.selected">{{post.name}}
</label>
<button ng-click="destroySelected()">Delete Selected Posts</button>
</div>


Custom Controller Function:

myApp.controller('PostController', ['$scope', function($scope) {

      // Initialize posts data
      $scope.posts = [
        { id: 1 , name: 'Manager',     selected: true },
        { id: 2 , name: 'Team Leader', selected: false },
        { id: 3 , name: 'Sr. Manager', selected: true },
        { id: 4 , name: 'Developer',   selected: false }
      ];

      // Delete selected posts
      $scope.destroySelected = function destroySelected(){
          angular.forEach($scope.posts, function (item) {

               // Check if post is selected
               if(item.selected === true){
                   // Delete the post with item.id 
                   alert('Deleted Post ID: '+item.id);
               }
          });
      } 
}]);

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

Verifying the Legitimacy of a Path in an Audio File

Attempting to play an audio file: path = '/public/recordings/weekday/1.mp3' const audio = new Audio(path) audio.play() If the path is invalid, a warning message appears in the console: Uncaught (in promise) DOMException: Failed to load because ...

Retrieve data from a JSON file URL using a GET request and save the response to be accessed globally when the Vue.js application is initialized

Consider this scenario - I have a Vue.js component where I need to display the name of a user based on their ID. The only information I have is the user's ID. However, I also have a JSON file URL that contains all the user objects with their names and ...

Moving a function from the controller to the directive

After examining my angular controller, I realized that it is expanding and should ideally focus on passing data. Currently, there is a function within my controller that calculates the number of months' worth of data displayed (within a 12-month peri ...

What is the reason behind JSON.parse returning null when the parameter is null?

When null is passed to JSON.parse, it returns null without any explanation in the documentation. Is there a specific reason for this behavior? Some other things to consider: This might be related to type conversion, as even passing JSON.parse("null") res ...

How to perfectly position an image within a fixed full screen container

When you click on a thumbnail image, a full-screen overlay with a larger version of the image will be triggered using JavaScript. To ensure that the image is centered and resized inside the black overlay when the browser window size changes, I attempted t ...

Transform your CSV data into JSON using Node.js and store it within a variable for easy access

Currently, I have this code snippet as a starting point and my task is to utilize it in order to convert the content of "world_data.csv" into JSON format. I am unsure of how to store this JSON data in a variable. I suspect that the desired data is tempora ...

Update the value of ng-show to false after redirection to the home page from the login page using AngularJS

I am new to angularjs and encountered a problem which required me to change the value of ng-show="false" to ng-show="true" when the user is redirected to the home page after successfully logging in! This is what I am attempting to achieve: .controller(&a ...

Rotate images with animation using Javascript

Seeking assistance with a swinging motion using two simple functions in Javascript. As a newcomer to the language, I am looking for guidance to achieve my goal. First function: function up() { imgObj.style.left = parseInt(imgObj.style.transform = 'r ...

Gather information on a webpage

I am attempting to extract a table from the following page "https://www.hkex.com.hk/Mutual-Market/Stock-Connect/Statistics/Historical-Monthly?sc_lang=en#select1=0&select2=0". After using the inspect/network function in Chrome, it appears that the data ...

Utilizing Visual Studio Code to efficiently eliminate unnecessary imports in an AngularJS project in one go

My current assignment involves tidying up our AngularJS project by eliminating any unused imports and variables. I typically use VS Code along with the TypeScript Hero extension (available at this link) to tackle this task one file at a time. But, I'm ...

Using createContext in React.tsx to pass the state through useState

There is a context called Transaction that accepts an object and a function as parameters. In the AppProvider component, the Transaction.Provider is returned. The following code snippet is from the GlobalState.tsx file: import { createContext, useState } f ...

Encountering difficulties in running bootstrap on nodejs

As a beginner in node.js and bootstrap, I am eager to create my own personal website, so I found some tutorials to help me get started. After downloading bootstrap 2.0.2 and unzipping it, I organized the files by placing bootstrap and bootstrap-responsive ...

Ionic's concealment feature fails to function properly for animations

I recently started learning about the Ionic framework and I'm attempting to incorporate a fade animation on a 'card' element using CSS. However, despite setting a 1-second transition duration, the targeted element simply disappears after a b ...

How to ensure Vue.js code modularity by preventing prop mutation within a child component?

After struggling with an unexpected mutation prop issue in a child component for quite some time, I stumbled upon this insightful quote: "When you have a component that receives an object through a prop, the parent is the one controlling that object, if ...

Update the Parent CRM Page upon closing the child ASP.net page

This pertains to CRM 2016 on-premise implementation. In my CRM 2016 environment, I have a customized button in the command bar that utilizes a JavaScript web resource to invoke an external asp.net page hosted on another server. This external page facilita ...

Combine strings in an array of objects

I have an array containing objects with a "Closed" property that holds numerical values. I want to loop through the array and concatenate all the "Closed" property values found in each object. For example, in the given array, the final result should be 12 ...

Passing parameters in a jQuery function through a button click

I am trying to figure out how to pass the @item.Id value as a parameter in the click function for a button. Here is the code snippet: <button id="buttonEdit" style="color:darkgreen" data-toggle="modal" data-target="#Ed ...

Discover the Power of Grouping by Distinct Names in D3

Data newdata = [ {'Name':'Andrew', 'Country':'US', 'Start date':'2012-7-2','Total':'30days' }, {'Name':'Kat', 'Country':'US', ' ...

Tips for effectively handling 404 errors when loading directive templates in AngularJS

When working with an AngularJS directive, the templateUrl parameter is dynamically specified. 'templates/' + content_id + '.html' I am looking for a way to handle situations where the value of content_id may not be valid or result in ...

Transform the array into a series of chained methods

I'm facing a challenge with an array structure that looks like this... $data = [ 'columns' => [ [['increments', 'id']], [['string', 'key'], ['index']], [[&apos ...