I am getting data from json file to display in a table, but first time only i got data from getdata() next time i got following error: Uncaught TypeError: Cannot read property 'length' of undefined Controller.js:95
$http return value is fine, i got all data from json file first time, next time i could not get data from getdata(). getData() function is not working properly, it is working only first time, next time i could not get data.
how to solve this issue.
controller.js
var app = angular.module('main', ['ngTable', 'claimApp']);
app.controller('DemoCtrl', function ($scope, $filter, ngTableParams, appFactory,$http) {
$scope.datasets = ["1", "2", "3"];
$scope.dataset = "1";
var data1 = [];
var data2 = [];
var data3 = [];
$scope.totalCnt = function () {
return window.document.getElementById("tablesort").getElementsByTagName("TR").length - 1;
};
var getData = function () {
if ($scope.dataset == "1") {
$http.get('json/json0.json').success(function(data) {
data1 = data;
});
return data1;
} else if ($scope.dataset == "2") {
$http.get('json/json1.json').success(function(data) {
data2= data;
});
return data2;
} else if ($scope.dataset == "3") {
$http.get('json/json2.json').success(function(data) {
data3= data;
});
return data3;
}
};
$scope.$watch("dataset", function () {
$("#tablesort").fadeOut('slow', function () {
$scope.tableParams.reload();
$scope.tableParams.page(1);
$("#tablesort").fadeIn('slow');
});
});
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
name: 'asc' // initial sorting
}
}, {
total: function () {
return getData().length;
console.info("==="+getData().length);
}, // length of data
getData: function ($defer, params) {
var filteredData = getData();
console.info("filteredData"+filteredData);<!--i could not get this data second time only it is working first time-->
var orderedData = params.sorting() ?
$filter('orderBy')(filteredData, params.orderBy()) :
filteredData;
var lastPage = (1 + Math.floor((orderedData.length - 1) / params.count()));
$("#lastpage").html(lastPage);
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
},
$scope: {
$data: {}
}
});
});
data1 = data;
use$scope.data1 = data;
and remove return statement. Same withdata2, data3
– Satpal Jul 16 '14 at 8:05