AngularJS ngtable not displaying data correctly - javascript

I have an ngTable that is loaded with data that proceeds from a "Get" call to a webapi. Then I reload the table, but the data it is not being displayed.
This is the *.js file
rdapp.controller('scoringTableCtrl', ['$location', '$scope', '$http', 'ngTableParams', '$filter',
function($location, $scope, $http, ngTableParams, $filter) {
$scope.teamList = [];
$http({
method: 'GET',
url: 'http://localhost:34592/api/scoringTable',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then(function(success) {
$scope.teamList = success.data;
addFieldsForSorting();
$scope.dataTable.reload();
}, function(error) {
console.log(error);
});
$scope.resolveHTML = function(position) {
if (position == 1 || position == 2 || position == 3) return 'champions';
if (position == 4) return 'champions-prev';
if (position == 5 || position == 6) return 'europa-league';
if (position == 18 || position == 19 || position == 20) return 'decline';
return '';
}
function addFieldsForSorting() {
// Add named properties for every stat value in recipients array, used for sorting the grid.
// Take value from vitalStats array, use alertIds to match between alpha keys and numeric keys.
$scope.teamList.forEach(function(team) {
for (var property in team) {
if (!team.hasOwnProperty(property)) {
continue;
}
if (property == 'name') {
continue;
}
if (property == 'position') {
continue;
}
var prop = 'sort_' + property;
team[prop] = -(team[property]);
}
team['sort_name'] = team.name;
team['sort_position'] = team.position;
});
}
$scope.dataTable = new ngTableParams({
page: 1, // show first page
count: 20, // count per page
sorting: {
sort_position: 'asc' // initial sorting
}
}, {
counts: [],
total: $scope.teamList.length, // length of data
getData: function($defer, params) {
// use build-in angular filter
var requestData = $scope.teamList;
var orderedData = params.sorting() ? $filter('orderBy')(requestData, params.orderBy()) : requestData;
params.total(orderedData.length); // set total for recalc pagination
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
}
]);
This is my html:
<div class="position-view" style="position:relative; top:100px;">
<table ng-table="dataTable" class="table table-bordered table-border-important" ng-class="rec_spinner">
<tbody class="text-center">{{$data.length}}
<tr ng-repeat="team in $data">
<td class="{{resolveHTML(team.position)}}" data-title="''" sortable="'sort_position'">
{{team.position}}
</td>
<td data-title="'Clasificación'" sortable="'sort_name'">
{{team.name}}
</td>
<!--Total Stats-->
<td data-title="'PJ'" sortable="'sort_pj'">
{{team.pj}}
</td>
<td data-title="'PG'" sortable="'sort_pg'" >
{{team.pg}}
</td>
<td data-title="'PE'" sortable="'sort_pe'" >
{{team.pe}}
</td>
<td data-title="'PP'" sortable="'sort_pp'" >
{{team.pp}}
</td>
<td data-title="'GF'" sortable="'sort_gf'">
{{team.gf}}
</td>
<td data-title="'GC'" sortable="'sort_gc'">
{{team.gc}}
</td>
<td data-title="'PT'" sortable="'sort_pt'">
{{team.pt}}
</td>
</tr>
</tbody>
</table>
$data has no any data, but if I try {{dataTable}} I have all the data correctly loaded. Can anybody help me with this?, maybe there is something obvious that I am missing, but the point is that the table is creating the amount of rows and columns anyway but empty, it is very weird.

I think you are not storing $data anywhere. I cannot find $scope.data in your js file.

After long search I figured out the problem was pretty easy, was about the CamelCase notation. The problem is when you send info from a web api, if you don´t set custom notation for the parameters, they will be sent with the first letter capitalized.
So, we have two chooses here, establish custom notation or just use in our HTML the first letter capitalized. I hope this will help somebody in the future!

Related

how to set an int value to a string in angular

I have a value in a table that is currently an int and I want to pass those variables to a table on a webpage but I want to change those values to actual names instead of numbers is there a way to do that by setting a scope in the controller and then pushing that string to the html?
for example:
This would be the html code for the table row and head and then the table data.
<thead>
<tr>
<th>Foo</th>
</tr>
</thead>
<tbody>
<tr ng-repeat= "x in names">
<td>{{ x.bar }}</td>
</tr>
</tbody>
I don't know the syntax for creating a scope for this in angular and then pushing that to the html or where it would go.
The table currently shows a 1 in the place of bar. I want it to actually say bar but register as 1. I don't know if that makes any sense.
I've seen some where they put
app.filter('thisfilter', function() {
return function (bar)
if((bar) || bar < 1){
return status_options;
}else{
var lastdigit = bar % 100;
if(lastdigit === 1){
return 'audi'
} else if(lastdigit === 2){
return 'bmw'
} else if(lastdigit === 3){
return 'mercedes'
} else if(last digit === 4){
return 'lexus'
}
}
}
and then they plug that back into the html
<td>{{ x.foo | thisfilter }}</td>
Here is a very contrived example to show the use of a filter to display text in place of a numeric value.
angular.module('app', [])
.filter('valueToText', () => {
return (input) => {
switch (input) {
case 1:
return 'bar';
case 2:
return 'foo'
default:
return input;
}
}
})
.controller('ctrl', ($scope) => {
$scope.names = [{
value: 1
}, {
value: 2
}, {
value: 2
}, {
value: 'foobar'
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<ul>
<li ng-repeat="x in names">{{x.value | valueToText}}</li>
</ul>
</div>

Issue with filtering an Angular Table td

I have a table created in angularJS.
HTML:
<div class="widget-content" ng-controller="getAllBenchersController">
<table ng-table="talentPoolList" show-filter="true"
class="table table-striped table-bordered">
<tr ng-repeat="employee in $data" | filter: testFilter">
<td data-title="'#'">{{$index + 1}}</td>
<td data-title="'Employee ID'" sortable="'employee.employeeNo'"
filter="{ 'employee.employeeNo': 'text' }">
{{employee.employee.employeeNo}}
</td>
<td data-title="'Current State'" sortable="'state.state'" filter="{ 'state.state': 'text' }"
ng-class="{ red: employee.state.state == 'Available', blue: employee.state.state == 'Blocked'}">
{{employee.state.state}}
</td>
</tr>
</table>
</div>
In the <td data-title="'Current State'">I want to apply a filter. I want to display only states returning values 'Available' and 'Blocked'.
My controller is :
myApp.controller('getAllBenchersController', ['$scope', 'employeeTalentPoolServices', 'dataTable', '$window', '$timeout', function ($scope, employeeTalentPoolServices, dataTable, $window, $timeout) {
employeeTalentPoolServices.getAllBenchers().then(function (result) {
$scope.data = result.data;
$scope.testFilter = function (item) {
return (item.state.state.toLowerCase() === 'available' || item.state.state.toLowerCase() === 'blocked');
}
});
The states generally return values -'Available', 'Blocked', 'Billed' and 'Rejected'. I want the table to only display states - 'Available' and 'Blocked'.
Please have a check and point out what I'm doing wrong.
If you want to display only the items with the state 'available' and 'blocked' i think the best choice is to apply an angular filter in the ng-repeat. By this way, the ng-repeat only computes the items needed for the table.
You can add a new filter, for example:
myApp.filter('filterState',
[], function() {
return function(items) {
return items.map(function(obj) {
if (obj.state === 'available' || obj.state === 'blocked')
return obj;
});
});
After, your div element should be:
<tr ng-repeat="employee in $data" | filter: filterState">
return (item.state.state.toLowerCase() === 'available' || item.state.state.toLowerCase() === 'blocked');
Above code returns a boolean value, also if you have array list of values , here only one value is considered.
You should write a for loop , then check the values.
Refer below code:
var filteredOutput=[];
for(var i=0;i<item.length; i++){
if(item[i].state.state.toLowerCase() === 'available' || item[i].state.state.toLowerCase() === 'blocked')
{
filteredOutput.push(item[i]);
}
}
return filteredOutput;

Get data from a key value structure and compare it with value from an ng-repeat in AngularJS

Two basic questions,
1) I have a controller where I define a list with a key, value structure and I want to access to the event name based on the eventID and log it in the console
$scope.events = [
{eventID:3200, eventName:"Event One"}
{eventID:3201, eventName:"Event Two"}
];
I tried this:
if($scope.events.eventID == 3200) {
console.log("Ok");
}
but it didnt worked :(
2) Then in my view I have a table where i print data coming from a WS, what I want is to print the description on the table depending on the eventID from my $scope.events list, I have a field on my ng-repeat named event that will let me compare with the eventID from the list but I dont know how to do this.
<tr ng repeat d in data>
<td>d.Description</td>
<td>d.anyValue</td>
</tr>
Any help is welcome, I really need it I'm new to Angular :)
Add method in controller
$scope.search=function(obj){
return obj.eventID === 3200;
}
add it to view
<tr ng-repeat="d in data | filter:search">
<td>d.Description</td>
<td>d.anyValue</td>
</tr>
for question number 1, try with this
if($scope.events[0].eventID == 3200) {
console.log("Ok");
}
for looping using this
angular.forEach($scope.events, function (value) {
if (value.eventId === 3200) {
{
console.log('OK');
}
});
for question number 2, create helper function to return eventName base on the ID.
$scope.getEventName = function (eventId) {
var result = '';
angular.forEach($scope.events, function (value) {
if (value.eventID === eventId) {
result = value.eventName;
return false;
}
});
return result;
}
<tr ng-repeat="d in (exportDataEventDesc.result.slice(5, exportDataEventDesc.result.length-2))">
<td>{{d.Description}}</td>
<td>{{d.anyValue}}</td>
<td ng-bind="getEventName(d.merchMetrics.EVENT_ID)" style="text-align: left"></td>
</tr>

NG Table no works with just 1 record

I´ve a problem about angularJS.
My ng-table no works when database comes just 1 record.
When is loaded 2 or more records works.
Browser error console:
Error: [orderBy:notarray] http://errors.angularjs.org/1.5.0/orderBy/notarray?p0=%7B%22clienteID%22%3A…clienteNome%22%3A%22Nicolas%22%2C%22clienteConta%22%3A%229.9999999E7%22%7D
at Error (native)
at
MY HTML:
<table ng-table="tableParams" class="table table-striped" show-filter="true">
<tr ng-repeat="cliente in data">
<td title="'ID'" filter="{ clienteID: 'number'}" sortable="'clienteID'">
{{cliente.clienteID}}
</td>
<td title="'Cliente'" filter="{ clienteNome: 'text'}" sortable="'clienteNome'">
{{cliente.clienteNome}}
</td>
<td><a ng-click="editUser(user.id)" class="btn btn-small btn-primary">Editar</a></td>
<td><a ng-click="deleteClienteById(cliente.clienteID)" class="btn btn-small btn-danger">Excluir</a></td>
</tr>
</table>
MY CONTROLLER:
angular.module('ProjetoAngularClient').controller('clienteController',
function($scope,$filter,NgTableParams,clienteService) {
clienteService.getAllClientes().success(function(response){
$scope.clientes = response.cliente;
table();
});
function getAll(){
clienteService.getAllClientes().success(function(response){
$scope.clientes = null;
$scope.clientes = response.cliente;
$scope.tableParams.reload();
});
}
function table(){
$scope.tableParams = new NgTableParams({
page: 1,
count:10
}, {
total: $scope.clientes.length,
getData: function ($defer, params) {
$scope.data = params.sorting() ? $filter('orderBy')($scope.clientes, params.orderBy()) : $scope.clientes;
$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.deleteClienteById = function(clienteID) {
clienteService.deleteClienteById(clienteID);
getAll();
};
});
Thanks for help
You need an array in all cases. However $scope.clientes = response.cliente; sets $scope.clientes to one single client.
I don't fully understand your program logic. At first you seem to load from clienteService.getAllClientes() and then call getAll(); via table() to again load clienteService.getAllClientes().
A quick fix would be to test if response.cliente is an array, and if not, assign it like $scope.clientes = [response.cliente];
However, I think your backend should be fixed to always return an array.

Apply ng-class to array of items in angularjs

I am trying to highlight multiple row select functionality, so that when a user click's on a row it highlight the row and when it again select that row it un-highlight that. But the problem I am facing is how to give array of items to ng-class.
Here is my code.
<tr ng-click="selectRow(1)" ng-class="{row_selected: ArrayOfItems}" class="ng-scope odd">
<td class="">
test
</td>
</tr>
And in my controller
$scope.selectedArray = [];
$scope.selectRow = function(id) {
if($scope.selectedArray.indexOf(id) == -1) {
$scope.selectedArray.push(id);
}else {
$scope.selectedArray.splice($scope.selectedArray.indexOf(id),1);
}
});
So what I am doing in controller is on clicking a row it push the id's in an array and on clicking the same row it pops out that id from array.
Any help ?
First check whether the row is selected or not
<tr ng-click="selectRow(1)" ng-class="{row_selected: isRowSelected(1)}" class="ng-scope odd">
<td class="">
test
</td>
</tr>
Add the isRowSelected to controller:
$scope.selectedArray = [];
$scope.isRowSelected = function(id) {
$scope.selectedArray.indexOf(id) != -1
}
$scope.selectRow = function(id) {
if($scope.selectedArray.indexOf(id) == -1) {
$scope.selectedArray.push(id);
}else {
$scope.selectedArray.splice($scope.selectedArray.indexOf(id),1);
}
});
More proper setup would be with in use of 'ng-repeat'. See the working code at:
JSFiddle
HTML:
<div ng-controller="MyController">
<table>
<tr ng-repeat="item in items" ng-click="selectRow(item)" ng-class="{row_selected: isSelected(item)}">
<td>
<a id="{{item}}">test {{item}}</a>
</td>
</tr>
</table>
</div>
JS/AngularJS:
var myApp = angular.module('myApp', []);
myApp.controller('MyController', ['$scope', function ($scope) {
$scope.items = [1,2,3,4,5];
$scope.selectedArray = [];
$scope.selectRow = function (id) {
if($scope.selectedArray.indexOf(id) == -1) {
$scope.selectedArray.push(id);
}else {
$scope.selectedArray.splice($scope.selectedArray.indexOf(id),1);
}
};
$scope.isSelected = function (id) {
if( $scope.selectedArray.indexOf(id) > -1){
return true;
}
return false;
};
}]);

Categories

Resources