AngularJs: uncheck checkbox after item is removed - javascript

after spending a lot of time on this simple issue and having made a lot of research, I was wondering if someone could give me some help.
I have data which is generated inside of a table like so:
<tbody>
<tr class="odd gradeX" ng-repeat="user in ctrl.datas | orderBy:ctrl.sortType:ctrl.sortTypeReverse">
<td>
<input type="checkbox" class="checkboxes" value="{{user.id}}" ng-click="ctrl.addItem(user)"/>
</td>
<td>
{{user.given_name}}
</td>
<td>
{{user.family_name}}
</td>
<td>
{{user.email}}
</td>
<td class="center" ng-bind-html="ctrl.convertToDate(user.created_at) | date: 'dd-MMMM-yyyy hh:mm'"></td>
<td>
<span class="btn blue-hoki"> Details </span>
</td>
</tr>
</tbody>
Above is a container where I get the items selected via a checkbox, add the in an array and give the user the ability to delete the selected item:
<tr ng-repeat="user in ctrl.checkedObject track by $index" ng-show="user.id">
<td>{{user.family_name}}</td>
<td>{{user.given_name}}</td>
<td>
<button class="btn blue" ng-click="ctrl.removeItem($index)">Unselect</button>
</td>
</tr>
In my controller, here are the two functions used to do so:
this.checkedObject = [];
//Add selected user
this.addItem = function (user) {
self.checkedObject.push(user);
};
this.removeItem = function(obj){
delete self.checkedObject[obj];
};
What i'd like to achieve is to uncheck the corresponding checkbox if a user changes his selection.
The thing is, I have no idea how to target the corresponding checkbox. Does anyone have a clue?
Thanks in advance

Try ng-checked like:
<input type="checkbox" ng-checked="user !== null" class="checkboxes" value="{{user.id}}" ng-click="ctrl.addItem(user)"/>
And set the item (user) to null on button click (inside removeItem() ) or a other variable.

I set up a simple plunker to show one approach, which would be to assign a selected property to each user when his/her checkbox is checked, and set an ng-checked attribute on the checkbox corresponding to user.selected (so will be unchecked when false).
Using this approach you won't need to push and delete from the array of checkedUsers, you can just filter all the users by whether they are selected or not.
function getSelected() {
ctrl.checkedObject = _.filter(ctrl.datas, {selected: true});
}
ctrl.selectUser = function (user) {
user.selected = true;
getSelected();
};
ctrl.removeUser = function(user){
user.selected = false;
getSelected();
};

Related

Get data from dynamically added elements and pass to Django request.POST

I have a restaurant_form which allows user to input menu items. Each menu item represent a table row which is added dynamically. Each table row has input for: menu item, price, halal(Boolean), and notes.
Here is a sample entry. data-ids and names of input elements are incremented.
<tbody class="menu-entry ">
<tr id='menu0' data-id="0" class="hidden">
<td data-name="name" class="name">
<input type="text" name='name0' placeholder='Menu Item' class="form-control"/>
</td>
<td data-name="price">
<input type="text" name='price0' placeholder='0.00' class="form-control"/>
</td>
<td data-name="halal">
<input type="checkbox" name="veg0" value="halal" class="form-control">
</td>
<td data-name="notes">
<textarea name="notes0" placeholder="Contains soy." class="form-control"></textarea>
</td>
<td data-name="del">
<button name="del0" class='btn btn-danger glyphicon glyphicon-remove row-remove'></button>
</td>
</tr>
</tbody>
What is the best way to retrieve data from the table? I have tried this:
$('#restaurant_form').submit(function () {
$('.menu-entry').each(function()
{
$(this).find('td').each(function(){
$(this).find("input").each(function() {
alert(this.value)
});
$(this).find("textarea").each(function() {
alert(this.value)
});
})
})
})
The alert() shows the correct values however I am wondering if there is a better way to do this?
Edit I simplified it using:
$('.menu-entry .form-control').each()
Also, after retrieving the values, how can I pass it to the view with a POST request? I would like to save the values to model
RestaurantMenu with columns name, price, halal and notes.
Thank you.
Here's what I did:
For every menu entry, I converted the values to a string separated by comma and added a hidden input to hold the value. I added class 'menu-row' to tr.
$('#restaurant_form').submit(function () {
$('.menu-row').each(function(){
var menu_entry = ""
$(this).find('.form-control').each(function(){
menu_entry = menu_entry + this.value + ","
})
$('#restaurant_form').append('<input type="hidden" name="menu_entries" value="'+ menu_entry +'" />')
alert(menu_entry)
})
})
In views.py :
menu_entries = request.POST.getlist('menu_entries')
for menu_entry in menu_entries:
entry = menu_entry.split(",")
if entry[1]:
price = round(float(entry[1]), 2)
else:
price = 0.00
if not entry[2]:
entry[2] = False
MenuItems.objects.create(name=entry[0], price=price, halal=entry[2], notes=entry[3], restaurant_id=r.id)
If anyone knows a better approach, I would love to know. Thank you!

How to calculate a value using checkbox AngularJs in a repeater

I use a ngRepeat with a checkbox and need when I check each item compute the value total of selected items as below:
HTML:
<tr ng-repeat="ciclo in ciclos">
<td><input id="idCiclo" type="checkbox" ng-click="computeTotal(ciclo)">
</td>
<td>{{ciclo.Quantity}}</td>
<td>{{ciclo.Value | currency}}</td>
...
<tfoot>
<tr>
...
<td>{{TotalQuantity}}</td>...
Controller:
$scope.computeTotal = function (ciclo) {
$scope.TotalQuantity += ciclo.Quantity; //Here I need Add or Subtract a value
};
You should have a property that indicates whether a checkbox has been checked or unchecked so that you can decide to add or subtract.
You would be using ngModel with ngChange (ngClick is usually better for elements that don't have built-in click expectations/behaviors).
Example:
View:
<tr ng-repeat="ciclo in ciclos">
<td>
<input class="ciclo" type="checkbox" ng-model="ciclo.checked" ng-change="computeTotal(ciclo)">
<!-- Note that I took out the ID. IDs should never be used in ngRepeat,
as it heavily risks multiple elements having the same ID,
which should ALWAYS be unique.
A class works much better for collections like this. -->
</td>
<td>{{ciclo.Quantity}}</td>
<td>{{ciclo.Value | currency}}</td>
</tr>
Controller:
$scope.computeTotal = function (ciclo) {
if(ciclo.checked)
$scope.TotalQuantity += ciclo.Quantity;
else
$scope.TotalQuantity -= ciclo.Quantity;
};

how to exchange date from one controller to another by using services in angularjs?

I want to get the selected data from the radio button and that particular data should be taken to that vote function and i need to view that data in another view or html by using the service.
How can i pass the values of selected attribute to another view using services?
Here is my code:
<body>
<table>
<tr id="$index" ng-repeat= "a in data ">
<td> {{a.condidateID}} </td>
<td> {{a.condidateName}} </td>
<td> {{a.territory}} </td>
<td> {{a.voteCount}} </td>
<td> <input type="radio" name="chickenEgg" value="egg" ng-model="chekratiovalue" ng-change="chengeEvnt($index)"></td>
</tr>
</table>
<button style="left: 40%;top: 40%;float: left;position: relative" ng-click="voteForPerson()">Vote</button
</body>
angular.module('Design')
.controller('MainCtrl',['profService',function($scope,profService) {
$scope.data = [{
condidateID:"1",
condidateName:"test",
territory:"APAC",
voteCount:"1",
chekratiovalue:"egg"
},
{
condidateID:"2",
condidateName:"test2",
territory:"APAC",
voteCount:"2",
chekratiovalue:"chicken"
}];
$scope.chengeEvnt = function(index) {
$scope.activeRow = index; // get the index when changing the radio button
var selected = $scope.data[$scope.activeRow]; // get the row of selected radio button using the `$scope.activeRow` function
}
$scope.voteForPerson = function() {
}
}]);

AngularJS, easy way to show a delete button when a checkbox is checked in the list of users under ng-repeat

I am trying to toggle a delete button which has already a function bound to it. The list is created with ng-repeat checking the users object. But the methds I have seen so far are either simple model show which does not work in my case. Or complex directive controller methods.
All I need is to check whether at least one checkbox is checked. Here is the snippet from the code:
<table class="table">
<tr ng-repeat="user in ctrl.commonUserService.users | filter:ctrl.commonUserService.suppressLoggedOnUserFilter()">
<td><input type="checkbox" ng-model="user.selected" value="y" /></td>
<td title="User Name"><strong>{{user.userName}}</strong></td>
How can I easily do this with Angular? I tried to create a function looping users and looking if they are selected at all but don't think I can put this function to ng-show.
You'll have to check if at least one box is selected when the state changes:
<td><input type="checkbox" ng-model="user.selected" ng-change="ctrl.userSelected()" value="y" /></td> <!-- use ng-change to notify when a checkbox is clicked -->
<button ng-click="ctrl.delete()" ng-show="ctrl.usersSelected">Delete</button> <!-- if ctrl.usersSelected is true show delete -->
In the controller:
this.userSelected = function userSelected() { // when checkbox is clicked check users to see if at least one is selected and save the state in this.userSelected
this.usersSelected = this.commonUserService.users.some(function(user) {
return user.selected;
});
};
You can do this fairly easily using the ng-change directive on your inputs. See this plunkr for the working example, but it basically goes like this:
View:
<table class="table">
<tr ng-repeat="user in users">
<td><input type="checkbox" ng-change="isSelected()" ng-model="user.selected" /></td>
<td title="User Name"><strong>{{user.userName}}</strong></td>
</tr>
</table>
<button class="delete" ng-show="showDelete">Delete</button>
Controller:
$scope.isSelected = function() {
var somethingSelected = false;
$scope.users.forEach(function(user, index) {
if (user.selected) somethingSelected = true;
});
$scope.showDelete = somethingSelected;
};

AngularJS - Nested ng-repeat for table

I just started with AngularJS and I'm trying to make a users table that shows the users for the application and the roles they are in (e.g. Admin, Editor, Anon) with checkboxes to take the users in and out of roles.
<tbody>
<tr data-ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">
<td class="table-item-title"><a title="{{item.UserName}}" href="" ng-click="loadEditForm(item.UserName)">{{item.UserName}}</a></td>
<td class="hmax479">{{item.Email}}</td>
<td align="center" data-ng-repeat="role in roles" style="align:center;">
<input type="checkbox" data-ng-model="role.IsChecked" style="align:center;"/>
</td>
</tr>
</tbody
With the above code it updates the checkboxes for the entire group based on the last user that was clicked rather than for a single user. Is there any way I can change this code with something like a "user in users" ng-repeat to change this or do I need to add a new function in the controller?
Each user could have an array of roles to show the roles that has been assigned to the user. For each user, while looping through the roles, you use a filter to only check assigned roles. You could use a function in your controller to add/remove roles as the check boxes are selected/deselected.
<tbody>
<tr data-ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">
<td class="table-item-title"><a title="{{item.UserName}}" href="" ng-click="loadEditForm(item.UserName)">{{item.UserName}}</a></td>
<td class="hmax479">{{item.Email}}</td>
<td align="center" data-ng-repeat="role in roles" style="align:center;">
<input type="checkbox" data-ng-checked="role | hasRole:item.Roles" data-ng-click="addOrRemove($parent.$index, role)" style="align:center;"/>
</td>
</tr>
</tbody>
The filter
app.filter('hasRole', function() {
return function (role, userRoles) {
var result = false;
userRoles.forEach(function(value, index) { // loop through the roles
// return true if the user has the role
if(role.Name == value.Name) // This is replaced by any method of comparing roles
result = true;
});
return result;
}
}
In your controller, you implement addOrRemove()

Categories

Resources