AngularJS - Form good practice - javascript

So I am new to AngularJS and I am looking to create good code because my application is going to scale.
Now, I have a list of competences that I'll get from my API, and then I need to make a list of them with a checkbox, so the user will select/deselect from the list, and then submit that form.
So how can I achieve that? What should be in the ng-model of every checkbox? Should I create a form with all the values in set in false?
Here's my controller code now:
function Controller(Competence) {
var vm = this;
vm.competences = [];
function initController() {
Competence.getAll()
.then(function(data) {
vm.competences = data;
});
}
initController();
}
And here's my view code:
<table>
<thead>
<tr>
<th width="90%">Competence</th>
<th width="10%">Select</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="competence in vm.competences">
<td>{{ competence.name }}</td>
<td><input type="checkbox"></td>
</tr>
</tbody>
</table>

So far your code looks good. To set checkbox values, just add ng-model="competence.selected" to each checkbox input element like this:
<input type="checkbox" ng-model="competence.selected">
Now when you select the checkbox it will set competence.selected to true, and when you deselect it the value will be false.
Form Submission
Wrap your table in a <form> with an ng-submit attribute, and create a function to submit the form:
<form ng-controller="MyCtrl as vm" ng-submit="vm.submitForm()">
<!-- your table here ... -->
<input type="submit" value="Submit">
</form>
In your controller:
vm.submitForm = function(){
vm.competences.forEach(function(competence){
if(competence.selected) console.log(competence);
// or POST the competences using the $http service ...
})
}
See JSFiddle also: Checkbox Demo

Related

Issue sending JSON from array to web service on Angular

I have a table. Every cell of the row tables are form fields. Also, I have two buttons: one button add a new row to the table and a second one whitch send all the rows.
This is for add new blank rows:
$scope.atributs =[];
$scope.addRow = function(){
var newRow = {nomAtribut: "",tipus: "",mida: "",prioritat: "",obligatori: "",observacions: ""};
$scope.atributs.push(newRow);
}
View :
<table class="table">
<tr>
<td>Nom atribut</td>
<td>Tipus</td>
<td>Mida</td>
<td>Prioritat</td>
<td>Obligatori</td>
<td>Observacions</td>
</tr>
<tr ng-repeat="atribut in atributs">
<td><input type="text" ng-model="atribut.nomAtribut" /> </td>
<td>
<select ng-options="option as option.valor for option in options" ng-model="atribut.tipus"></select>
</td>
<td><input type="number" ng-model="atribut.mida" /></td>
<td>
<select ng-options="option as option.valor for option in options" ng-model="atribut.tipus"></select>
</td>
<td><input type="checkbox" ng-model="atribut.obligatori" ng-true-value="'YES'" ng-false-value="'NO'"></td>
<td><input type="text" ng-model="atribut.observacions" /> </td>
</tr>
</table>
Angular Code for sending data to web Service :-
$scope.sendRow = function(){
$http.post("http://10.0.203.73/WS/ws.php/tipusactius/alta", $scope.atributs).success(function(data){
$scope.status = data;
})
}
Json Array Sending:-
[{"nomAtribut":"j",
"tipus":{"idvalors_combo":"3","valor":"Date"},
"mida":11,"prioritat":"",
"obligatori":"YES",
"observacions":"fcefwq"}]
Is all correct and the problem come from the web service? or the angular code is wrong? It's my first try with angular. Thank you.
So it looks like your web service wants a single element from your data array at a time.
I think you should modify the sendRow function to take the row index you want to send, like so:
$scope.sendRow = function(atributRow){
$http.post("http://10.0.203.73/WS/ws.php/tipusactius/alta", atributRow).success(function(data){
$scope.status = data;
})
}
Then, you can send all rows in a loop by:
angular.forEach($scope.atributs, $scope.sendRow);
or a single row with a specific index:
$scope.sendRow($scope.atributs[0])

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;
};

jQuery code to get checkbox length while using jQuery DataTables

I am getting wrong value while fetching the checkbox length using jQuery and jQuery DataTables.
HTML:
<table class="table table-bordered" id="dataTables-show-productList">
<thead>
<tr>
<th width="5px"><input type="checkbox" name="Select All" class="chkSelectAll" /></th>
<th>Product Information</th>
</tr>
</thead>
<tbody>
<c:forEach var="masterListVar" items="${masterList}">
<tr>
<td width="1%" align="center">
<c:if test="${masterListVar.saveFlag}">
<input type="checkbox" path="selectChecked" checked class="Projection_test" value="${masterListVar.productId}"/>
</c:if>
<c:if test="${!masterListVar.saveFlag}">
<input type="checkbox" path="selectChecked" class="Projection_test" value="${masterListVar.productId}"/>
</c:if>
</td>
<td>${masterListVar.productInfo}</td>
</tr>
</c:forEach>
</tbody>
</table>
JavaScript:
$('#dataTables-show-productList').DataTable({
width:'100%'
, responsive : true
, "bSort" : false
});
$('.chkSelectAll').click(function () {
$('.Projection_test').prop('checked', $(this).is(':checked'));
});
$('.Projection_test').click(function () {
if ($('.Projection_test:checked').length == $('.Projection_test').length) {
$('.chkSelectAll').prop('checked', true);
}
else {
$('.chkSelectAll').prop('checked', false);
}
});
$('#FavouriteList').click(function (e) {
var selectedRow = $('.Projection_test');
alert($('.Projection_test:checked').length);
e.preventDefault();
});
When paginating, while selecting only 12 values. in the alert it showing only 2 when i kept in the 2 page and testing.
CAUSE
With jQuery DataTables only visible rows exist in DOM. That is why accessing checkboxes with jQuery $() method gives you 2 nodes.
SOLUTION
To select checkboxes including those that don't exist in DOM and taking into the account current search query, use the code below:
// Select all available rows with search applied
var rows = $('#dataTables-show-productList').DataTable()
.rows({ 'search': 'applied' })
.nodes();
// Checked checkboxes
console.log($('.Projection_test:checked', rows).length);
// All checkboxes
console.log($('.Projection_test', rows).length);
You need to use this logic in all click event handlers: $('.chkSelectAll').click, $('.Projection_test').click and $('#FavouriteList').click.
NOTES
jQuery DataTables also has $() method that allows to perform a jQuery selection action on the full table. However it doesn't allow to filter out rows with search applied.
See our article jQuery DataTables – How to add a checkbox column for more information on how to work with checkboxes when using jQuery DataTables.

Remove invalid row from table

I've table with inline create (when user click on new button it create new empty row first in the table, which he can put data inside),when user click on save I go to the controller and check if this values are valid,if yes store them on the DB.if not I raise exception to the UI and not store the data.The problem is that the new row is not stored but I see it in the UI. just when I refresh the page in the browser the line was omitted..
My question is if there is a way by code search for the first line of the table and remove it explicitly from the UI?
I try like the following but its not refresh the table,any idea?
$("table:first").find("tr:first").remove();
The following should work with a general table.
HTML
<table>
<tbody>
<tr>
<td>row1</td>
</tr>
<tr>
<td>row2</td>
</tr>
<tr>
<td>row3</td>
</tr>
</tbody>
</table>
<br />
<br />
<input type="submit" id="btnAdd" value="add"></input>
<input type="submit" id="btnRemove" value="remove"></input>
jquery
$(function () {
$("#btnAdd").click(function () {
$("table:first > tbody").prepend('<tr><td>new row</td></tr>');
});
$("#btnRemove").click(function () {
$("table:first tr:first-child").remove();
});
});
Working example: http://jsfiddle.net/5NxL4/

Get column in a row in a table if that row has a selected checkbox

I have a table like the following
<table id="adminTable">
<thead>
<tr>
<th></th>
<th>Username</th>
<th>Email</th>
<tr>
</thead>
<tbody>
<tr><td><input type='checkbox' name='selected_users[]' value='User1'/></td><td>User1</td><td>mail1#mail.com</td></tr>
<tr><td><input type='checkbox' name='selected_users[]' value='User2'/></td><td>User2</td><td>mail2#mail.com</td></tr>
...
</tbody>
</table>
I have a button below which calls a javascript-function.
This function then should get all the emails for the users which were selected via their checkboxes...
I am quite new to Javascript and jQuery an am not sure of how to achieve this...
But I can use plain Javascript or use jQuery...
What I already found was this, but I can't get it to help me, because I don't want a button in my row (multiple selections shall be possible via the checkboxes).
You can use the following function which run on a button click:
$(":button").click(function() {
var emails = $("input[name=selected_users[]]:checked").map(function() {
return $(this).closest("td").next("td").text();
}).get();
console.log(emails); //array of emails that were checked
});
$("#adminTable").find("td").filter(function()
{
return $(this).find("input[type=checkbox]:checked").length > 0;
});
Keep in mind you have TR tags in your html that don't have closing tags and are out of place.

Categories

Resources