我想稍微清理我的AngularJS代码。现在,我在$ scope。[array]下的JS文件中有我的JSON数组,共有5组。我可以将它们全部放在一个单独的JSON文件中,还是每个阵列都需要多个文件?如果我将它们放在一个JSON文件中,我仍然可以通过$http.get()
访问它们吗?
这是带有JSON数据的JS代码:
var reportApp = angular.module('reportApp', ['ui.bootstrap']);
reportApp.controller('reportController', function($scope) {
$scope.head = [
{id: 1, name: 'Application Name', class: 'filtersearch'},
{id: 2, name: 'Date Created'},
{id: 3, name: 'Date Updated'},
{id: 4, name: 'Payload'},
{id: 5, name: 'Status', class: 'filtersearch'},
{id: 6, name: 'Error Code', class: 'filtersearch'},
{id: 7, name: 'Error Description'}
];
$scope.details = [
{id: 1, name: 'Application Name'},
{id: 2, name: 'Error Description'},
{id: 3, name: 'Record Count'},
{id: 4, name: 'Record Fail'}
];
$scope.status = [
{id: 1, name: 'Active'},
{id: 2, name: 'Inactive'},
{id: 3, name: 'Unknown'}
];
$scope.errorCode = [
{id: 1, name: 'Code01'},
{id: 2, name: 'Code02'},
{id: 3, name: 'Code03'},
{id: 4, name: 'Code04'}
];
$scope.apps = [
{appName: 'App01',
dateCreated: '01/01/2015',
dateUpdated: '01/04/2015',
payload: 'Payload01',
status: $scope.status[0],
errorCode: $scope.errorCode[0],
errorDesc: 'Desc01',
recordCount: 1,
recordFail: 1},
{appName: 'App01',
dateCreated: '01/02/2015',
dateUpdated: '01/05/2015',
payload: 'Payload02',
status: $scope.status[0],
errorCode: $scope.errorCode[1],
errorDesc: 'Desc02',
recordCount: 1,
recordFail: 2},
{appName: 'App03',
dateCreated: '01/03/2015',
dateUpdated: '01/06/2015',
payload: 'Payload03',
status: $scope.status[1],
errorCode: $scope.errorCode[2],
errorDesc: 'Desc03',
recordCount: 2,
recordFail: 1}
];
});
我希望以类似于下面代码的方式使用$http.get()
,但对于多个数组:
var report = this;
report.apps = [];
$http.get('apps.json').success(function(data){
report.apps = data;
});
非常感谢任何输入!
编辑:这是JS Fiddle。
var report = this;
report.apps = [];
$http.get('../controllers/apps.json').success(function(data){
for (head in data) {
report.head = data.head;
}
for (details in data) {
report.details = data.details;
}
for (status in data) {
report.status = data.status;
}
for (errorCode in data) {
report.errorCode = data.errorCode;
}
for (apps in data) {
report.apps = data.apps;
}
});
答案 0 :(得分:2)
您可以将它们放在一个对象下:
{ head : [
{id: 1, name: 'Application Name', class: 'filtersearch'},
{id: 2, name: 'Date Created'},
{id: 3, name: 'Date Updated'},
{id: 4, name: 'Payload'},
{id: 5, name: 'Status', class: 'filtersearch'},
{id: 6, name: 'Error Code', class: 'filtersearch'},
{id: 7, name: 'Error Description'}
],
details : [
{id: 1, name: 'Application Name'},
{id: 2, name: 'Error Description'},
{id: 3, name: 'Record Count'},
{id: 4, name: 'Record Fail'}
]
}
然后迭代该对象,并分配给store:
$http.get('../store-products.json').success(function(data){
for (key in data) {
store[key] = data[key];
}
});