angularjs remove Selected Items using splice Function - javascript

I was looking for a solution to remove items from the Grid; that's why I posted the question before. But when I got the solution from someone, at that time, I thought it solved the issue, but it was using a Filter method.
However, I want the items to be removed from the GRID using a Splice Function.
Here is my old Question Link
Angularjs, Applying Action on Selected Checkboxes in Table
I want it to execute using a Splice Function.
Right now the problem I am facing is to pass the index value to the function so that the item can be deleted if that index value is selected/fetched. I am not sure how to fix it.
It would be nice if someone solves the problem and gives a demo link to the updated code.
Here is the Plunker Link for what I have tried so far.Plunker link to show my execution

Definition of JS array.splice method (from MDN):
array.splice(index , howMany[, element1[, ...[, elementN]]])
So, your removefunction should be written as:
$scope.remove = function(index){
$scope.students.splice(index, 1);
};
DEMO PLUNKER
EDIT:
I figured you wanted to remove the items by clicking the "x" button with ng-click pointing to remove function.
To remove the items by clicking the checkbox you should set checkbox ngModel to a student property and than put a $watcher on students that would remove those students who have this property set to true:
<tr class="color2" ng-repeat="student in students | filter:search | filter:new_search">
<td>{{student.Rollno}} <input type="checkbox" ng-model="student.checked"> </td>
<td>{{student.Name}}</td>
<td>{{student.Uni}} <button ng-click="remove($index)">x </button></td>
</tr>
$scope.$watch('students', function(students){
if(!students){
return;
}
$scope.students = students.filter(function(student){
return !student.checked;
});
}, true);
PLNUKER

I have added ng-click to checkbox to make it working
http://plnkr.co/edit/DSVPj3holsf4nhNvEMbQ?p=preview

Related

How to two-way bind a checkbox using Angular?

I currently have an accordion with a bunch of options in the form of checkboxes. The user can select the checkboxes as expected however, I want to already have some of those checkboxes checked depending on certain conditions. The issue is sometimes that is determined after the page has loaded. Below are simplified examples to demonstrate my code (my code is for work and would not be able to share due to confidentiality issues).
My HTML looks like this:
<div class="row">
<div "ngFor="let value of filteredPeople" >
<div>
<input type="checkbox" (click)="selectPeople(value)" [checked]="checkedPeople.get(value)">
{{ value }}
</div>
</div>
</div
My Javascript:
public checkPeople() {
this.selectedPeople.forEach(element => {
this.checkedPeople.set(element, true);
});
}
To explain some variables and methods:
Variables:
filterPeople - a string array of all possible people
checkedPeople - a map with a KVP of string (the people) and boolean (whether or not their checkbox is checked)
selectedPeople - a string array of people whose checkboxes I want already checked
Methods:
selectPeople - checks the corresponding checkbox when user clicks on it
checkPeople - a method called when I want the specific checkboxes checked (these specific checkboxes change based on other factors so I cannot hard code it)
For some reason my checkPeople method does not seem to select the expected checkboxes, I am not sure why but I have a feeling it is to do with the fact that I have used "[checked]" in the HTML and that it should be something else. Can someone clarify the issue for me and help me identify a fix? (Note: as the title suggests, I am using Angular)
Edit:
I have just debugged my code and added breakpoints, the checkedPeople map has the correct mapping of people to true for each of the elements in selectedPeople which shows that the checkPeople method is working as expected. Therefore the issue must be with the [checked] attribute if I'm not mistaken. I cannot see why it wouldn't work though.
You should use [ngModel]="checkedPeople.get(value)"
instead of [checked]="checkedPeople.get(value)"
to initialize the checkbox and
(change)="checkUncheckPeople(value, $event)"
to update the value when you check or uncheck it, where
checkUncheckPeople(value, e) {
this.checkedPeople.set(value, e.target.value);
}
So, in conclusion, your HTML input element will be:
<input
type="checkbox"
[ngModel]="checkedPeople.get(value)"
(change)="checkUncheckPeople(value, $event)"
/>
If you choose to use an object instead of a map then you can also directly use
[(ngModel)]="checkedPeople[value]"
to two-way bind the variable

Toggle with ! operator not working on page load JavaScript

I have an onClick (using angular.js ng-click) where i have to toggle color of a table row with on click.
This is the initial implementation.
<tr>
<td ng-class="{'setType': types.isTypeSet('TYPE') == true}" ng-click="types.setType('TYPE')">
<img class="typebox-img" src="">
<div class="typebox">TYPE</div>
</td>
</tr>
where 'type' is the type of table row and 'types' is the angular controller.
types.setType(type):
...
this.types[type] = ! this.types[type];
...
while this toggles values from the second click on, it doesnt change the value on the first click.
I implemented the functionality using the if-else statement, but cant figure out why this wont work as it is a pretty basic thing to do.
this.types[type] is set to false as default.
Could someone explain why is this happening..
It doesn't surprise me that this doesn't work:
ng-click='types.setType('type')
Use " for the inner quotes to make the parser understand what you're trying to do (or the other way around):
ng-click='types.setType("type")'
Incidentally, you don't need a function to do this. Just initialize in your controller a bool:
$scope.toggle = true
And use in your view like this:
ng-click='toggle = !toggle'

Copy an item from an array to another array on click event in AngularJS

I have a list of food items. The food items are made from JSON files read into an array called $scope.foodlist.
Each food item has a checkbox called "favourite". When it's checked I want to make a copy of the food item and place it in a separate div called "favourites". I suspect the best way to do this will be to have an array $scope.favourites and to add a food item to this array when its checkbox is clicked, and remove it when its checkbox is not clicked.
On the checkbox, I have:
<input type="checkbox" ng-click="addFavourite($event)" />
Right now, for the function I have this:
$scope.addFavourite = function(event) {
$scope.clicked= "clicked";
};
This prints out the word "clicked" to {{ clicked }} in the template.
How can I pass the knowledge of which food item has just been clicked, to the function addFavourite()?
Plunkr here
Some guys provided a tutorial how to deal with checkboxes in AngularJS:
Answer: https://stackoverflow.com/a/14520103/1477415
Tutorial http://jsbin.com/ImAqUC/1
Just pass extra argument to addFavourite function. Here is an example:
Passing multiple argument to ng-click method

Cloning table row in Jquery

Running into a bit of a brick wall with jquery, I currently have the following code:
http://jsfiddle.net/uSLhb/1/
The clone method being:
$("#addMore").click(function() {
$('.user_restriction:last').clone().insertAfter(".user_restriction:last");
return false;
});
As you can see I have it set up so you can easily clone the row.
The problem I am facing is showing the correct select list (In the 'Field' column) in the new cloned elements, depending on what field they select from the first select (In the 'table' column) field in the row.
Wondering if anyone can help me find a solution, thanks!
The problem you are facing occurs, because you are using IDs for your selects.
IDs must be unique in a page, otherwise you'll run into trouble. If you're cloning a select with an id, the id will be cloned too, thus producing an invalid document.
Have a look at the example I created on JsBin
Markup:
<tr class="user_restriction">
<td>
<select name="table[]" class="userselect">
<option value="" selected>---</option>
<option value="members">Members</option>
<option value="staff_positions">Staff Positions</option>
</select>
</td>
<!-- and so on, basically just changed ids to classes -->
</tr>
I changed all the IDs to classes and altered the change-handler, because this was your second problem.
An event-handler gets bound to the elements that are selected, not to those you add afterwards. This is a proper use-case for event-delegation, when the handler is bound to a parent and catches, in this example, the change event from a child select-element, no matter when it was added to the DOM.
Using jQuery, this is a way to achieve this:
$('table.table').on('change', '.userselect', function() {
var activeRow = $(this).parents('tr');
activeRow.find('td').eq(1).find('select').hide();
if(this.value.length === 0){
activeRow.find('td').eq(1).find('select').eq(0).show();
}else{
activeRow.find("." + this.value).show();
}
});
The handler is bound to your table - element, .userselect is a class I added to the first select in a row. So every change on an element that was added later would be handled too. In the handler, I changed the behaviour to affect only the actual table-row, not the whole table.
Working example here - I had to use jsbin as fiddle was playing up!
Clone does not maintain the selected state, so you'll need to grab the value before cloning and set it after.
Your click now becomes:
$("#addMore").click(function() {
var value = $('.user_restriction:last').find('select').val();
$('.user_restriction:last').clone().insertAfter(".user_restriction:last");
//alert(value);
$('.user_restriction:last').find('select').val(value);
return false;
});

Sorting column with check boxes. Doesn't work. I am stuck

I would like that the Signed button in this JSfiddle sorts the column with the check boxes, like it actually does perfectly.
http://jsfiddle.net/littlesandra88/DSRmg/
I noticed that tinySort, the library used to sort the tables, can't sort the column with just the check boxes, so I added a (or X in the JSfiddle for visability) for those <td>'s that have the check box checked, and it could sort the column.
Problem
The problem is, that when Save is clicked the or X in this case, should be added, so when Signed is clicked, the column is sorted correctly.
In this post learned I how to add and remove &nbsp or X.
It seams to me that JQuery can't find the <label>, because it is inside a <td>.
How to reproduce problem
Try un-checking one of the checkboxes and click Signed. Now the check box column is not sorted correctly any longer.
Question
How do I get the Save buttons to add a , so the column can be sorted?
Update
In this have I implemented Rakesh's answer of tablesort. But I still can't get it to work.
I would suggest you to use tablesorter plugin which gives you an option to have your own parser logic for sorting.
Take a look at the code - http://jsfiddle.net/srakesh/DSRmg/8/
HTML:
<td class="checkbox"> <input name="signed" type="checkbox" checked ><span class="hidden">1</span> </td>
Javascript:
$(document).ready(function() {
$("#myTable").tablesorter();
$('#myTable input:checkbox').click(function() {
var order = this.checked ? '1' : '0';
$(this).next().html(order);
$(this).parents("table").trigger("update");
})
});
missing a semi colon:
$('#myTable input:checkbox').click(function() {
var order = this.checked ? '1' : '0';
$(this).next().html(order);
$(this).parents("table").trigger("update");
}); //try putting a semicolon here

Categories

Resources