CRUD issue while edit and save from table using angularjs - javascript

When i tried to click the edit radio button the details will be displayed in the concerned boxes but the existing details in the table is deleted. Here my requirement is to use single array/scope variable for edit, display and delete. But no use for loop while edit/delete. Here i done the changes but no proper way of work. my html index.html as follows
<div ng-controller="employeeController">
<header><h1>Employee Details</h1></header>
<form name="myForm" novalidate>
<table id="myTable" cellspacing="0" cellpadding="4">
<tr>
<td><label> Employee Id </Label></td>
<td><input type="text" name="eid" data-ng-model="employees.EmployeeId" data-ng-required="true" ng-disabled="newEmployees"/></td>
</tr>
<tr>
<td><label> FirstName </Label></td>
<td><input type="text" name="fname" data-ng-model="employees.FirstName" data-ng-required="true"/></td>
</tr>
<tr>
<td><label> LastName </Label></td>
<td><input type="text" name="lname" data-ng-model="employees.LastName" data-ng-required="true"/></td>
</tr>
<tr>
<td><label> Gender </Label></td>
<td>
<input type="radio" name="gender" data-ng-change="employees.Gender" value ="Male" data-ng-model="employees.Gender"/> Male
<input type="radio" name="gender" data-ng-change="employees.Gender" value ="Female" data-ng-model="employees.Gender"/>Female
</td>
</tr>
<tr>
<td><label> Email </Label></td>
<td><input type="text" name="email" data-ng-model="employees.Email" data-ng-required="true"/></td>
</tr>
<tr>
<td><label> Account </Label></td>
<td><input type="text" name="account" data-ng-model="employees.Account" data-ng-required="true"/></td>
</tr>
<tr>
<td><input type="hidden" data-ng-model="employees.EmployeeId"></td>
</tr>
</table>
<button name="btnSave" data-ng-click="saveEmployeeRecord(employees)" class="userbutton">Save</button>
<button name="btnReset" data-ng-click="resetEmployeeRecord()" class="userbutton">Reset</button>
</form>
<table border="2" cellspacing="0" cellpadding="4">
<tr style="color: blue">
<th style="width:100px">Employee Id</th>
<th style="width:150px">FirstName</th>
<th style="width:150px">LastName</th>
<th style="width:90px">Gender</th>
<th style="width:150px">Email</th>
<th style="width:60px">Account</th>
<th>Action</th>
</tr>
<tr style="color:green" data-ng-repeat="emp in employees">
<td>{{emp.EmployeeId}}</td>
<td>{{emp.FirstName}}</td>
<td>{{emp.LastName}}</td>
<td>{{emp.Gender}}</td>
<td>{{emp.Email}}</td>
<td>{{emp.Account}}</td>
<td>
<input type="radio" name="process" data-ng-click="editEmployee(emp, employees.indexOf(emp))"> Edit
<input type="radio" name="process" data-ng-click="DeleteEmployee(employees.indexOf(emp))"> Delete
</td>
</tr>
</table>
</div>
javascript app.js
var employeeApp = angular.module("myApp",[]);
employeeApp.controller("employeeController", function($rootScope, $scope, $http) {
$http.get('data/employees.json').success(function(data) {
$rootScope.employees = data;
});
var empId = 12342;
$rootScope.saveEmployeeRecord = function(emp) {
if($rootScope.employees.EmployeeId == null) {
$rootScope.employees.EmployeeId = empId++;
$rootScope.employees.push(emp);
}
else {
for(i in $rootScope.employees) {
if($rootScope.employees[i].EmployeeId == emp.EmployeeId) {
$rootScope.employees[i]= emp;
}
}
}
//$rootScope.employees = {};
}
$rootScope.resetEmployeeRecord = function() {
angular.copy({}, $rootScope.employees);
}
$rootScope.editEmployee = function(emp, indx) {
//$rootScope.emp = $rootScope.employees;
if($rootScope.employees[indx].EmployeeId == emp.EmployeeId) {
$rootScope.employees = angular.copy($rootScope.employees[indx]);
}
}
$rootScope.DeleteEmployee = function(idx) {
var result = confirm("Are you sure want to delete?");
if (result) {
$rootScope.employees.splice(idx,1);
return true;
}
else {
return false;
}
//for(i in $rootScope.employees) {
//if($rootScope.employees[i].EmployeeId == idx) {
//$rootScope.employees = {};
//}
//}
}
});
employees.json file:
[
{
"EmployeeId": "61234",
"LastName": "Anderson",
"FirstName": "James",
"Gender": "Male",
"Email": "james_anderson#infosys.com",
"Account": "Boeing"
},
{
"EmployeeId": "512458",
"LastName": "Cambell",
"FirstName": "Mike",
"Gender": "Male",
"Email": "mike.cambell#infosys.com",
"Account": "Boeing"
},
{
"EmployeeId": "712785",
"LastName": "Swachengar",
"FirstName": "Andrew",
"Gender": "Male",
"Email": "andrew.swachengar#infosys.com",
"Account": "Cisco"
},
{
"EmployeeId": "712734",
"LastName": "Anderson",
"FirstName": "James",
"Gender": "Male",
"Email": "james.anderson#infosys.com",
"Account": "Apple"
},
{
"EmployeeId": "61245",
"LastName": "Green",
"FirstName": "Rachael",
"Gender": "Female",
"Email": "rachael_green#infosys.com",
"Account": "Boeing"
},
{
"EmployeeId": "61347",
"LastName": "Brown",
"FirstName": "Jackualine",
"Gender": "Female",
"Email": "jackualine_brown#infosys.com",
"Account": "Boeing"
}
]

You need to assign the selected item to a model which you have to associate in your edit/save form. And then when "save" is clicked, you need to update the original data with the updated data. Here's an example of how that would work:
$rootScope.saveEmployeeRecord = function() {
for(k in $scope.selectedEmployee){
$scope.selectedEmployee[k] = $scope.selectedEmployeeCopy[k];
}
}
$rootScope.resetEmployeeRecord = function() {
$rootScope.selectedEmployeeCopy = null;
}
$rootScope.editEmployee = function(emp) {
$rootScope.selectedEmployee = emp;
$rootScope.selectedEmployeeCopy = angular.copy($rootScope.selectedEmployee);
}
Here, I am making a copy of your original employee, and updating the copy. When saved, the copy will replace the original employee. When cancelled, it will be simply ignored. Here's a working fiddle based on your code.
Edit: based on feedback, updated the save and delete method which were not working as expected. Also updated the jsFiddle.
Edit2: Removed for loops and relpaced with passing array index
$rootScope.saveEmployeeRecord = function() {
$rootScope.employees.splice($rootScope.selectedIndex, 1,$rootScope.selectedEmployeeCopy);
}
$rootScope.resetEmployeeRecord = function() {
$rootScope.selectedEmployeeCopy = null;
$rootScope.selectedIndex = null;
}
$rootScope.editEmployee = function(emp, ind) {
$rootScope.selectedIndex = ind;
$rootScope.selectedEmployee = emp;
$rootScope.selectedEmployeeCopy = angular.copy($rootScope.selectedEmployee);
}
$rootScope.DeleteEmployee = function(emp, ind) {
var result = confirm("Are you sure want to delete?");
if (result) {
$rootScope.employees.splice(ind, 1);
$rootScope.selectedEmployeeCopy = null;
$rootScope.selectedIndex = null;
return true;
}
else {
return false;
}
}

You can Pass id as like this with your index in your radio button.
<button class="btn btn-default" ng-click="editBook(add.id, $index);" type="submit">Edit</button>
See my controller:
$scope.editBook = function(id,index) {
$scope.show1=false;
$scope.show=true;
$http.get(appurl + 'user/adds/' + id + '.json')
.success(function(data, status, headers, config) {
$scope.user= data;
angular.copy($scope.user, $scope.copy);
});
};

Related

Filttering json data in html-table

I have to display json data in HTML-table and have succeeded in it. My problem is that I also need to filter this data by genders and studyfields using radiobuttons and dropdown list in the webpage. I have managed to do so but the filters clash with each other and mess the results in the table.
HTML:
<div>
<h4>Filter by Gender</h4>
<label>All</label>
<input class="filter-by-gender" checked="checked" type="radio" id="filterByGenderAll" value="all" name="filter_by_gender">
<label>Males</label>
<input class="filter-by-gender" type="radio" id="filterByGenderM" value="male" name="filter_by_gender">
<label>Females</label>
<input class="filter-by-gender" type="radio" id="filterByGenderF" value="female" name="filter_by_gender">
<br><br>
<h4>Filter by Studies</h4>
<select id="filterByStudiesAll" input class="filter-by-studies" name="filter-by-studies">
<option value="All" name="filter-by-studies">All</option>
<option value="Computer Science"name="filter-by-studies">Computer science</option>
<option value="Business"name="filter-by-studies">Business</option>
<option value="Art"name="filter-by-studies">Art</option>
</select>
</div>
<table id="students">
<thead>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Studyfield</th>
<th>Email</th>
<th>Phone</th>
<th>Address</th>
</thead>
<tbody class="tbody" id="personsTable">
</tbody>
</table>
Json is like this:
var students = [
{
"student_id": "123456",
"age": 20,
"firstname": "Horne",
"lastname": "Hess",
"gender": "male",
"study_field": "Computer Science",
"email": "hornehess#magnafone.com",
"phone": "+1 (877) 436-3132",
"address": "745 Livingston Street, Cassel, South Dakota, 103"}]
and lastly javascript:
function filterStudentsByGender(gender)
{
var filteredStudents = students
switch(gender)
{
case "male":
filteredStudents = students.filter(function(student){
return student.gender === "male"
})
break;
case "female":
filteredStudents = students.filter(function(student){
return student.gender === "female"
})
break;
}
var studentsHtml = filteredStudents.map(function(student){
return '<tr><td>'+student.firstname+" "+student.lastname+'</td><td>'+student.gender+'</td><td>'+student.age+'</td><td>'+student.study_field+"</td><td>"+student.email+"</td><td>"+student.phone+"</td><td>"+student.address+"</td></tr>";
})
$("#students").find('.tbody').html(studentsHtml)
}
function filterStudentsByStudy(study_field)
{
var filteredStudents=students
switch(study_field){
case "Computer Science":
filteredStudents=students.filter(function(student){
return student.study_field=="Computer Science"
})
break;
case "Art":
filteredStudents=students.filter(function(student){
return student.study_field=="Art"
})
break;
case "Business":
filteredStudents=students.filter(function(student){
return student.study_field=="Business"
})
break;
}
var studentsHtml = filteredStudents.map(function(student){
return '<tr><td>'+student.firstname+" "+student.lastname+'</td><td>'+student.gender+'</td><td>'+student.age+'</td><td>'+student.study_field+"</td><td>"+student.email+"</td><td>"+student.phone+"</td><td>"+student.address+"</td></tr>";
})
$("#students").find('.tbody').html(studentsHtml)
}
/* ########################## event listeners */
$(".filter-by-studies").on("change", function(e){
var checked = $(this).val();
filterStudentsByStudy(checked)
})
$(".filter-by-gender").on("change", function(e){
var checkedValue = $(this).val();
filterStudentsByGender(checkedValue)
})

Display json data in html table using jQuery

How to display json data in html table using jQuery ? and How can i remove case sensitive while searching the result?
expected output
How can i display the result in my table? How can i achieve this?
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for (i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].indexOf(skills) !== -1) || (data[i]["email"] === email) || (
data[i]["username"] === username)) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
var output = getResult();
console.log(output);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
You need to create a table and need to append coming data to this table using below code:-
$('#submit').click(function onClick() {
var output = getResult();
var html = '';
$.each(output,function(key,value){
html +='<tr>';
html +='<td>'+ value.username + '</td>';
html +='<td>'+ value.email + '</td>';
html +='<td>'+ value.skills + '</td>';
html +='</tr>';
});
$('table tbody').html(html);
});
To do case-insensitive comparison use .toUpperCase()
Working snippet:-
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for (i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].toUpperCase().indexOf(skills.toUpperCase()) !== -1) || (data[i]["email"].toUpperCase() === email.toUpperCase()) || (
data[i]["username"].toUpperCase() === username.toUpperCase())) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
var output = getResult();
var html = '';
$.each(output,function(key,value){
html +='<tr>';
html +='<td>'+ value.username + '</td>';
html +='<td>'+ value.email + '</td>';
html +='<td>'+ value.skills + '</td>';
html +='</tr>';
});
$('table tbody').html(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
<br>
<table>
<thead>
<tr>
<th>Username</th>
<th>Email ID</th>
<th>Core Skills</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
You can use Data-table jQuery plugin to generate table from jsondirectly like
$('#tableId').DataTable({
data: jsonData,
columns: [
{ data: 'username',title:'Username'},
{ data: 'emailId',title:'EmailId'},
{ data: 'skils',title:'Core Skills'}
],
"search": {
"caseInsensitive": false
}
});
For More detail follow Data-table jQuery Plugin.
Here is the code
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
function BindDataToTable(d,obj){
var keys=Object.keys(d[0]);
var table=document.createElement("table");
var trHead=document.createElement("tr");
jQuery(keys).each((index,item)=>{
var th=document.createElement("th");
th.innerHTML=item;
trHead.appendChild(th)
})
table.appendChild(trHead)
for(var i=0;i<d.length;i++){
var tr=document.createElement("tr");
jQuery(keys).each((index,item)=>{
var td=document.createElement("td");
td.innerHTML=d[i][item];
tr.appendChild(td)
})
table.appendChild(tr)
}
jQuery(obj).append(table);
}
BindDataToTable(data,"#tableElement")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
<div id="tableElement">
</div>

How to display the JSON data in a table depending on search?

I'm trying to display the data in the table depending on search. How can I achieve this?
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="skills">
<input type="email" placeholder="mail id">
<input type="text" placeholder="username">
<input type="submit" value="submit">
Expected o/p:
search any field ex:
input: java,
output :john and jane profiles
input:sql
output: only jane profile //he is the person who has sql skill
if nothing matches show 0 results
User can search using any one field, if any one item matches that profile should be displayed in my table. How can I do this? Can anyone please help me sort it out?
/* Dataset*/
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for(i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].indexOf(skills) !== -1) || (data[i]["email"] === email) || (data[i]["username"] === username)) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
console.log(getResult()); // print expected data
});
<script
src=
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
in ES6 you can do it :
results = array.filter (x=>x.username.search(search_txt));
let my_list = [{"username":"John Doe","email":"jn#gmail.com","skills":"java,c,html,css"},{"username":"Jane Smith","email":"js#gmail.com","skills":"java,sql"},{"username":"Chuck Berry","email":"cb#gmail.com","skills":"vuejs"}];
results = my_list.filter (x => x.skills.search('java')!=-1);
console.log(results);
//result is : [{"username":"John Doe","email":"jn#gmail.com","skills":"java,c,html,css"},{"username":"Jane Smith","email":"js#gmail.com","skills":"java,sql"}]
<!DOCTYPE html>
<html>
<head>
<title>SEARCH</title>
</head>
<body>
<input type="text" placeholder="skills" id="skills">
<input type="email" placeholder="mail id" id="email">
<input type="text" placeholder="username" id="username">
<input type="submit" value="submit" id="submit">
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Skills</th>
</tr>
<tr id="search">
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
$('#submit').click(function(){
var skills = $('#skills').val();
var email = $('#email').val();
var username = $('#username').val();
if(username){
search(username);
}
});
function search(username){
var name = username;
var html ;
data.forEach(function(currentValue, index, array){
if(currentValue.username == name){
html = "<td>"+currentValue.username+"</td>"+
"<td>"+currentValue.email+"</td"+
"<td>"+currentValue.skills+"</td>"
;
}else{
html = "Result Not Found";
}
});
return $('#search').html(html);
}
</script>
</body>
</html>
You can make a search function for skills like this:
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
var skills = "java,c";
function search(){
result = [];
var setSkills = skills.split(","); console.log(setSkills);
data.map((current,index)=>{
let currentSkills = current.skills.split(","); //console.log(currentSkills);
// currentSkills = ["java", "c", "html", "css"]
// setSkills = ["java", "c"] ;
// length of set currentSkills == length of set (currentSkills + setSkill) --> mean setSkills is subset of currentSkills
let bool = Array.from(new Set(currentSkills) ).length == Array.from(new Set(currentSkills.concat(setSkills)) ).length;
if(bool)
console.log(data[index]);
});
}
<input type="text" placeholder="skills">
<input type="email" placeholder="mail id">
<input type="text" placeholder="username">
<input type="submit" onclick="search();" value="submit">

Toggle class is not stable for table's cells

I am using toggle class for highlighting table cells.
<style>
table td.highlighted {
background-color: #999;
}
</style>
<script>
$(function () {
var isMouseDown = false;
$("#productTable td")
.mousedown(function () {
isMouseDown = true;
debugger;
$(this).toggleClass("highlighted");
return false; // prevent text selection
});
$(document)
.mouseup(function () {
debugger;
isMouseDown = false;
});
});
</script>
And my table is like this:
<div class="container">
<div class="row">
<form>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-search"></i>
</div>
<input type="text" class="form-control" placeholder="Aramak İstediğiniz Ürün Alanını Giriniz" ng-model="src_product">
</div>
</div>
</form>
</div>
<div class="row">
<div class="col-md-10">
<br />
<table ng-table="usersTable" id="productTable" class="table table-striped">
<tr>
<th ng-repeat="column in cols">{{column}}</th>
<th> Adet</th>
</tr>
<tr ng-repeat="row in data | filter: src_product">
<td id="productProperties" ng-model="productProperties" ng-repeat="column in cols ">{{row[column]}}</td>
<td><input type="text" style="width: 100%; height: 30px !important" name=" adet" value="0"></td>
</tr>
</table>
</div>
</div>
</div>
this is my controller:
myApp.controller('productController', ['$rootScope', '$scope', 'SharedDataService', "productFactory", "$log", "$filter", 'ngTableParams', function ($rootScope, $scope, SharedDataService, productFactory, $log, $filter, ngTableParams) {
$scope.users = [{"id":1,"first_name":"Philip","last_name":"Kim","email":"pkim0#mediafire.com","country":"Indonesia","ip_address":"29.107.35.8"},
{"id":2,"first_name":"Judith","last_name":"Austin","email":"jaustin1#mapquest.com","country":"China","ip_address":"173.65.94.30"},
{"id":3,"first_name":"Julie","last_name":"Wells","email":"jwells2#illinois.edu","country":"Finland","ip_address":"9.100.80.145"},
{"id":4,"first_name":"Gloria","last_name":"Greene","email":"ggreene3#blogs.com","country":"Indonesia","ip_address":"69.115.85.157"},
{"id":50,"first_name":"Andrea","last_name":"Greene","email":"agreene4#fda.gov","country":"Russia","ip_address":"128.72.13.52"},{"id":1,"first_name":"Philip","last_name":"Kim","email":"pkim0#mediafire.com","country":"Indonesia","ip_address":"29.107.35.8"},
{"id":2,"first_name":"Judith","last_name":"Austin","email":"jaustin1#mapquest.com","country":"China","ip_address":"173.65.94.30"},
{"id":3,"first_name":"Julie","last_name":"Wells","email":"jwells2#illinois.edu","country":"Finland","ip_address":"9.100.80.145"},
{"id":4,"first_name":"Gloria","last_name":"Greene","email":"ggreene3#blogs.com","country":"Indonesia","ip_address":"69.115.85.157"},
{ "id": 50, "first_name": "Andrea", "last_name": "Greene", "email": "agreene4#fda.gov", "country": "Russia", "ip_address": "128.72.13.52" },
{ "id": 1, "first_name": "Philip", "last_name": "Kim", "email": "pkim0#mediafire.com", "country": "Indonesia", "ip_address": "29.107.35.8" },
{ "id": 2, "first_name": "Judith", "last_name": "Austin", "email": "jaustin1#mapquest.com", "country": "China", "ip_address": "173.65.94.30" },
{ "id": 3, "first_name": "Julie", "last_name": "Wells", "email": "jwells2#illinois.edu", "country": "Finland", "ip_address": "9.100.80.145" },
{ "id": 4, "first_name": "Gloria", "last_name": "Greene", "email": "ggreene3#blogs.com", "country": "Indonesia", "ip_address": "69.115.85.157" },
{ "id": 50, "first_name": "Andrea", "last_name": "Greene", "email": "agreene4#fda.gov", "country": "Russia", "ip_address": "128.72.13.52" }];
$scope.usersTable = new ngTableParams({
page: 1,
count: 10
}, {
total: $scope.users.length,
getData: function ($defer, params) {
$scope.data = params.sorting() ? $filter('orderBy')($scope.users, params.orderBy()) : $scope.users;
$scope.data = params.filter() ? $filter('filter')($scope.data, params.filter()) : $scope.data;
$scope.data = $scope.data.slice((params.page() - 1) * params.count(), params.page() * params.count());
$defer.resolve($scope.data);
}
});
$scope.cols = Object.keys($scope.users[0]);
$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
debugger;
$scope.idSelectedVote = idSelectedVote;
};
$scope.src_product = '';
}]);
My table is looking like this:
Here is the my question. when i search a word or go second page of table highlighted cells are turn back non highligted and it doesnt let me select a cell. How can i do stable cells and take highlighted cells values ?
On page change or search, the table is redrawn so your class change is lost. If you assign the class based on a model value, you could instead change the model value and get the class modified, and this would be persisted across redraws. You can use ng-class attribute to make the class name used for the td dependant on a model value. For example:
<td ng-class="{'highlighted':row[column].isSelected}" ng-click="selectCell(row[column])"></td>
Then, inside your controller, you can create a function:
$scope.selectCell = function(cell) {
typeof cell.isSelected === "undefined" ? cell.isSelected = true : cell.isSelected = false;
}
ngClass
ngClick

AngularJs Table Sorting when Data is nested

How can I approach table sorting in angularjs, when my data is nested and not all columns are first level citizens of the objects.
Data (excerpt)
[
{
"name": "Team A",
"categories": [
{
"label": "FG%",
"value": 4676,
"points": 7
},
{
"label": "FT%",
"value": 8387,
"points": 9
}
]
}, {
"name": "Team B",
"categories": [
{
"label": "FG%",
"value": 5285,
"points": 10
},
{
"label": "FT%",
"value": 6111,
"points": 1
}
]
}
]
HTML
<div ng-controller="mainCtrl">
<table class="table table-striped table-condensed">
<thead>
<tr>
<th ng:click="changeSorting('name')">Name</th>
<th ng:click="changeSorting('name')">Points</th>
<th ng:click="changeSorting(value.label)" ng-repeat="(index, value) in data.teams[0].categories">{{value.label}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="team in data.teams | orderBy:sort.column:sort.descending ">
<td>{{team.name}}</td>
<td>{{team.totalPoints}}</td>
<td ng-repeat="(name, cat) in team.categories">
{{cat.value}}
</td>
</tr>
</tbody>
</table>
</div>
Here is a approach I found a few times. Anyway, because of the structure of my data, I am afraid this isn't the right idea.
Sorting on Controller
$scope.sort = {
column: 'name',
descending: false
};
$scope.changeSorting = function(column) {
var sort = $scope.sort;
if (sort.column == column) {
sort.descending = !sort.descending;
} else {
sort.column = column;
sort.descending = false;
}
};
Here is the updated fiddle: http://jsfiddle.net/SunnyRed/mTywq/2/
I modified your code based on angular documentation at http://docs.angularjs.org/api/ng.filter:orderBy
HTML
<div ng-controller="mainCtrl">
<table class="table table-striped table-condensed">
<thead>
<tr>
<th ng:click="predicate = 'name'; reverse = !reverse">Name</th>
<th ng:click="predicate = 'totalPoints'; reverse = !reverse">Points</th>
<th ng:click="toggleSort($index)" ng-repeat="category in data.teams[0].categories">{{category.label}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="team in data.teams | orderBy:predicate:reverse">
<td>{{team.name}}</td>
<td>{{team.totalPoints}}</td>
<td ng-repeat="(name, cat) in team.categories">
{{cat.value}}
</td>
</tr>
</tbody>
</table>
</div>
Sorting parts
$scope.toggleSort = function(index){
$scope.reverse = !$scope.reverse;
$scope.predicate = function(team){
return team.categories[index].points;
}
}
Here is the fiddle: http://jsfiddle.net/mgalela/Br5Wb/14/
Since you need to lookup the correct category based on it's label and then sort using it's associated value I'd create a custom orderBy function.
To use new function sortFunc we add it here:
<tr ng-repeat="team in data.teams | orderBy: sortFunc ">
Then let the user pick options:
<select ng-model="sortVal">
<option value="name">Name</option>
<option value="points">points</option>
<option value="3PM">3PM</option>
<option value="PTS">PTS</option>
</select>
Finally here's the sort function which pulls in the chosen option using $scope.sortVal and returns the appropriate value for orderBy to sort.
$scope.sortFunc = function(val) {
if ($scope.sortVal == 'name') {
return(val.name);
} else if ($scope.sortVal == 'points') {
return(val.totalPoints);
} else if ($scope.sortVal == '3PM' ||
$scope.sortVal == 'PTS') {
for (var i = 0; i < val.categories.length; i++) {
category = val.categories[i];
if (category.label == $scope.sortVal){
return(category.value);
}
}
}
}
Here's the fiddle of this working: http://jsfiddle.net/mTywq/4/

Categories

Resources