NG Table no works with just 1 record - javascript

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.

Related

Custom Service not giving desired result in controller in AngularJS 1.8

I have to debug a snippet written in AngularJS.
//===== service ==
app.service('allUserService', function($http) {
var config = {
headers: {
'X-XSRF-TOKEN': gettingValueFromSomewhere()
}
};
this.getAll = function() {
var restUrl = CONTEXT_PATH + '/rest/path/mypath';
return $http.get(restUrl, config).then(function(response) {
console.log(response.data.body); // console prints an Array which is correct
return response.data.body;
});
}
});
//========= controller ====
app.controller('UserCtrl', function($scope,allUserService) {
var valueArray = [];
valueArray = allUserService.getAll();
console.log(valueArray);
$scope.faqBook = valueArray;
});
allUserService :I am getting correct result from Rest webservie and console log shows desired return (an Array)
faqUserCtrl : I am not getting desired value in console log. Pls help me in finding the issue. It should have an array. I am expecting an Array in $scope.faqBook.
Important to Note, when I return a hardcoded array from allUserService, the code works fine
<div class="container" ng-app="UserModule" ng-controller="UserCtrl">
<p>Search : <input type="text" ng-model="search"/></p>
<table id="mainTable" class="table table-striped table-hover">
<tr ng-repeat="x in faqBook | filter:search">
<td><ul class="list-group"><li class="list-group-item">Question: {{ x.question }}</li><li class="list-group-item"> Answer: {{ x.answer }}</li></ul></td>
</tr>
</table>
</div>

AngularJS ngtable not displaying data correctly

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!

Promises dont get resolved. Alasql doesnt import CSV

I cant figure out what the error is. I try to read out a CSV from my server and then to access the DateValues with an FUnction Called getZinsAnDatum.
The Chain begins in function:
$scope.calcZins = function database(ctrl, $scope) {....
I chained the results, reading out my CSV-Values via
getZinsAnDatum(dateee, fullDate)
works when I click twice or wait and click again. Guess it works, after clicking two times, because its load into the cache. The function itself returns a promise too, after i get Warning from this, pointing on the code lines from getZinsAnDatum(dateee, fullDate):
Warning: a promise was created in a handler at /localhost:8383/validations/js/index.js:269:17 but was not returned from it
Sorry if I miss fundamental concepts.
I guess the Promises arent chained right or its to much traffic, because for every Value i detect (about 200) it downloads the hole CSV? therefore I wanted to inject the CSV once in my Alasql database and work from there.
But putting it in doesnt seem to work. Therefore could you help me out maybe? Down my code HTML and javascript:
I spared out some functions and variables, all variables are given and defined.
Javascript:
/* global $scope, user,user.anpDat, user.zinsDiff, user.zinsJetz,user.zinsNext, user.nextAnpDat, user.AnzahlAnMonatenZwischenErsterAnpassungUndAktuellemDatum , user.Berechnung, ctrl.Berechnung, Promise, alasql*/
angular.module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache']).controller('AppCtrl', function ($scope) {
this.fullDate = new Date("1999-12-20");
this.fullDate2 = new Date("2000-01-20");
this.fullDate3 = new Date("2010-03-19");
this.date = fullDate.toISOString().substring(0, 10);
this.date2 = fullDate2.toISOString().substring(0, 10);;
this.date3 = fullDate3.toISOString().substring(0, 10);;
var data = {};
var url = 'tests/fib.csv';
function getZinsAnDatum(dateee, fullDate) {
return new Promise(function (resolve, reject) {
alasql.promise('SELECT [1] FROM CSV("tests/fib.csv", {headers:false, }) WHERE [0] >=? AND [1]!="."', [dateee])
.then(function (data) {
var temp = data [1 ][1];
resolve(temp);
}).catch(function (err) {
console.log('Error:', err);
});
});
}
$scope.calcZins = function database(ctrl, $scope) {
this.mybase = new alasql.Database('mybase');
this.mybase.exec('CREATE TABLE one ');
this.mybase.exec('SELECT [0][1] INTO one FROM CSV("tests/fib.csv", {headers:false, })');
//this.mybase.exec('PRINT one'); //GIVES ERRORS, CANT READ UNDEFINED JSON Object
calcZins2(ctrl, $scope);
;
}
function calcZins2(ctrl, $scope) {
var user = new Object;
var anpassen = false;
user = angular.copy(ctrl);
user.Berechnung;
var Row;
getZinsAnDatum(user.date2, user.fullDate2).then(function (resu) {
// Code depending on result
var value = parseFloat(resu.replace(",", "."));
user.zinsJetz = value;
Row.zinsJetz=user.zinsJetz;
user.Berechnung.push(Row);
nextAbschnitt(user, ctrl, $scope);
}).catch(function () {
// An error occurred
});
function nextAbschnitt(user, ctrl, $scope) {
getZinsAnDatum(date3,fullDate3).then(function (resulte) {
// Code depending on result
var value = parseFloat(resulte.replace(",", "."));
user.zinsNext = value;
getZinsAnDatum(date, FullDate).then(function (result) {
// Code depending on result
var value3 = parseFloat(result.replace(",", "."));
user.zinsJetz = value3;
gO(user, ctrl, $scope);
}).catch(function () {
// An error occurred
});
}).catch(function () {
// An error occurred
});
}
}
function getMonthsDifference(date1, date2) {
var k = date1.getYear() * 12 + date1.getMonth();
console.log(k + "k")
var m2 = date2.getYear() * 12 + date2.getMonth();
console.log(m2 + "m2")
return (m2 - k + 1);
}
function gO(user, ctrl, $scope) {
var g = getMonthsDifference(user.date2 user.date3);
user.AnzahlAnMonatenZwischenErsterAnpassungUndAktuellemDatum = g;
var count = 0;
var promiseFor = Promise.method(function (condition, action, value) {
if (!condition(value))
return value;
return action(value).then(promiseFor.bind(null, condition, action));
});
promiseFor(function (count) {
return count < user.AnzahlAnMonatenZwischenErsterAnpassungUndAktuellemDatum;
}, function (count) {
// ctrl.Berechnung = user.Berechnung;
return getZinsAnDatum(date3, fullDate3 ).then(function (resulte) {
// DO STUFF
ctrl.done = true; // Shows THE HTML div via ng-Show
ctrl.Berechnung = user.Berechnung;
return ++count;
});
}, 0).then(function (user) {
});
}
});
HTML:
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr><td>Zinssatz nach richtiger Anpassung:</td><td> {{ctrl.zinssatzKorrekt}}</td></tr>
<tr><td>Aktueller Zinssatz der Bank</td><td>{{ctrl.zinssatzAktuell}}</td></tr>
<tr><td>Differenz: </td><td>{{ctrl.zinssatzAktuell-ctrl.zinssatzKorrekt}}</td></tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr> <tr> </tr>
<tr>
<td>FIBOR/EURIBOR-Stichtag</td><td>maßgeblicher FIBOR/EURIBOR in %</td><td>FIBOR/EURIBOR-
Veränderung</td> <td>Veränderung
kumuliert</td> <td>Anpassung</td> <td>gebotene
Anpassung</td> <td>Zinssatz korrekt</td></tr>
<tr ng-class="Texttype" ng-repeat="row in ctrl.Berechnung track by $index">
<td> {{row.anpDat}}</td><td>{{row.zinsJetz}} </td><td>{{row.zinsDiff}} </td> <td>{{row.veranderungKummuliert}} </td> <td>{{row.anpassen}} </td> <td>{{row.geboteneAnpassung}} </td> <td>{{row.zinssatzKorrekt}} </td></tr>
</table>

AngularJS ng-init not working with ng-repeat

I've been trying to call passID() function when page initializes but the function still doesn't work.
The website works this way:
Page-A passes data to Controller-A
then to Service then to Controller-B then the function from Controller-B gets called by Page-B.
My guess is that my error is in Page-B since I've successfully passed the data of Page-A up to Controller-B but I'm not 100% sure.
In my Page-A, I've made a button calling the function of Controller-A using ng-Click
<button class="viewDetails" ng-click="passID([1,03,07])">test button</button>
Controller-A only gets data from Page-A
angular.module('handsetExplorerModule')
.controller("compareHandsetController", ['$scope','compareHandsetService','sharedData', function($scope, compareHandsetService, sharedData) {
$scope.passID = function(id){
var arrayID = [];
arrayID = id;
sharedData.set(arrayID);
};
}]);
Service gets my JSON and is my getter and setter
angular.module('handsetExplorerModule')
.factory('compareDetailsService', ['$http','$q', function($http, $q) {
return {
getHandsetList: function(){
return $http.get("./data/compareJSON.json");
}
};
}]);
angular.module('handsetExplorerModule')
.factory('sharedData', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
Controller-B filters the JSON file to only get what I need (i used ID from Page-A to filter)
angular.module('handsetExplorerModule')
.controller("compareDetailsController", ['$scope','compareDetailsService','sharedData', function($scope, compareDetailsService, sharedData) {
$scope.data = {phones: []};
compareDetailsService.getHandsetList()
.then(
function(data){
$scope.data.phones = data.data;
},
function(error){
//todo: handle error
}
);
var getData = sharedData.get();
$scope.passID = function passID(){
var newData = [];
for(var i=0; i<$scope.data.phones.length; i++){
if($scope.data.phones[i].id == getData[0] || $scope.data.phones[i].id == getData[01] || $scope.data.phones[i].id == getData[02]){
newData.push($scope.data.phones[i]);
}
}
$scope.phoneContent = newData;
}
$scope.viewDetails = function(id){
alert(id);
}
}]);
Lastly, In my Page-B, I've called Controller-B function: <div ng-init="passID()">
to be used by ng-repeat of my Page-B:
<table id="Content" ng-repeat="x in phoneContent track by x.id">
<tr>
<td class="one">
<table>
<tr>
<td><img class="contImage" ng-src="{{x.image}}" ng-alt="{{x.name}}" /></td>
<td class="textAlign">{{x.name}} <button class="viewDetails" ng-click="viewDetails(x.id)">VIEW DETAILS</button></td>
</table>
</td>
<td class="two">{{x.size}}</td>
<td class="one">{{x.storage}}</td>
<td class="two">{{x.camera}}</td>
<td class="one">{{x.battery}}</td>
<td class="two">{{x.network}}</td>
<td class="one">{{x.sim}}</td>
</tr>
</table>
I don't know why you define arrayID.
To solve your problem try with sharedData.set = arrayID; instead of sharedData.set(arrayID);.
Hope it helps!

AngularJs : how to do a $watch on a function to evoid the error: $digest() iterations reached

I have a list with items. Each item of a list can be selected. If I select the item, it will be pushed in the cookies.
In my home.html (here I have the list with the items that I can add to cookies)
<table class="table" >
<tr data-ng-repeat="item in items">
<td><span >{{item.title}}</span></td>
<td> <button data-ng-click="addToCookies(item)" data-ng-disabled="item.added" class="btn">
<span data-ng-show="!item[$index].added" class="text-center">Add To cookies</span>
<span data-ng-show="item[$index].added" class="text-center">Added To cookies</span>
</button>
</td>
</tr>
<tr></tr>
</table>
In page cookies.html I call the getCookiesItem() and the directive :
<div class="navbar navbar-right" data-ng-controller="ctrlItemsList">
<div data-item-list data-items="getCookiesItem()" ></div>
</div>
In my controller I did :
//TO ADD ELEMENT SELECTED IN THE COOKIE
$scope.addToCookies = function (item){
item.added=true;
angular.extend($scope.criteria, item);
cookiesItems.addItem($scope.criteria);
}
//TO GET ELEMENTS COOKIE (MAYBE I HAVE TO DO A $WATCH OF THIS FUNCTION)
$scope.getCookiesItem = function (){
return cookiesItems.getItems();
}
In my service I have :
Cservices.factory('cookiesItems', ['$cookieStore', function($cookieStore) {
var items = [];
return {
addItem: function( itemSelected){
var array = [];
if ($cookieStore.get('key') === undefined) {
$cookieStore.put('key', []);
}else{
array = $cookieStore.get('key');
}
array.push(itemSelected);
$cookieStore.put('key', array);
},
removeItem: function(itemSelected){
var array = $cookieStore.get('key');
if(array != undefined){
for (var i = 0; i < array.length; ) {
if (array[i].id=== itemSelected.id) {
array.splice(array[i], 1);
} else {
++i;
}
}
}
$cookieStore.put('key', array);
},
getItems: function(){
return $cookieStore.get('key');
}
The elements cookies are print in the following directive:
template :
<table class="table" >
<tr data-ng-repeat="item in items">
<td>{{item.title}}</td>
</tr>
<tr></tr>
</table>
in the js :
iDirective.directive('itemList', function() {
return {
restrict: 'A',
transclude: true,
scope: {
items: '=items'
}
templateUrl: ''
};
});
I have the following error:
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["fn: parentValueWatch; newVal: [{
and when i try to add the 10' element in the cookies I have this error (only 9 element I am able to store): Cookie '' possibly not set or overflowed because it was too large (4263 > 4096 bytes)! -
I am not able to resolve it..someone can help me?
Thanks
It would be helpful if you could put together a jsfiddle example.
From your code I can see the following issue.
In the ng-repeat section either should use 'items[$index]' or just 'item'.
<table class="table" >
<tr data-ng-repeat="item in items">
<td><span >{{item.title}}</span></td>
<td> <button data-ng-click="addToCookies(item)" data-ng-disabled="item.added" class="btn">
<span data-ng-show="!item.added" class="text-center">Add To cookies</span>
<span data-ng-show="item.added" class="text-center">Added To cookies</span>
</button>
</td>
</tr>
<tr></tr>
</table>
What is the method addToCookies exactly doing? What is $scope.criteria object? It looks like you always modify and add the same object to the cookieItems.
$scope.addToCookies = function (item){
item.added=true;
angular.extend($scope.criteria, item); // what is $scope.criteria?
cookiesItems.addItem($scope.criteria); // will always the same object added to the cookieItems?
$scope.selectedItems.push(item); // why do you have a second list and why you add 'item' and not 'criteria'?
}

Categories

Resources