我从json文件中获取数据以显示在表中,但是第一次只有我在下次出现以下错误时从getdata()获取数据: 未捕获的TypeError:无法读取未定义的Controller.js:95的属性'length'
$ http返回值很好,我第一次从json文件获取所有数据,下次我无法从getdata()获取数据。 getData()函数不能正常工作,它只是第一次工作,下次我无法获取数据。
如何解决这个问题。
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: {}
}
});
});
答案 0 :(得分:0)
根据文件
Request transformations:
If the data property of the request configuration object contains an object, serialize it into JSON format.
Response transformations:
If XSRF prefix is detected, strip it (see Security Considerations section below).
If JSON response is detected, deserialize it using a JSON parser.
请在回复中使用
$http.get('json/json0.json').success(function(data) {
data1 = JSON.parse(data);
});
修改强>
var getData = function () {
if ($scope.dataset == "1") {
$http.get('json/json0.json').success(function(data) {
$scope.response = data;
});
} else if ($scope.dataset == "2") {
$http.get('json/json1.json').success(function(data) {
$scope.response = data;
});
} else if ($scope.dataset == "3") {
$http.get('json/json2.json').success(function(data) {
$scope.response = data;
});
}
return $scope.response;
};