如何从数据库记录中创建json数组

时间:2015-12-19 19:34:28

标签: angularjs json

我正在使用angularjs从数据库中获取对象的json数组,但只有最后一条记录显示else没有显示。

var myApp=angular.module('myApp',[]);
myApp.controller('Controller',['$scope','$http',function($scope,$http) {
$scope.getAllMedicine = function(){
    $http.get('http://localhost:8080/Webapp/webapi/medicine/all').success(function(data){
        for(j=0; j<data.length; j++){
            $scope.medicineList = [{
                "medicineId" : "Id : " + data[j].medicineId,
                "medicineName" : "Name : " + data[j].medicineName,
                "medicinePotency" : "Potency : "+ data[j].medicinePotency,
                "medicinePrice" :"Price : " +data[j].medicinePrice,
                "medicineQuantity":"Quantity : " +data[j].medicineQuantity
            }
            ]
        }
    });
}
}]);

任何人都可以告诉我我犯的错误,我应该感恩:)

1 个答案:

答案 0 :(得分:1)

更新
for(j=0; j<data.length; j++){
    $scope.medicineList = [{
        "medicineId" : "Id : " + data[j].medicineId,
        "medicineName" : "Name : " + data[j].medicineName,
        "medicinePotency" : "Potency : "+ data[j].medicinePotency,
        "medicinePrice" :"Price : " +data[j].medicinePrice,
        "medicineQuantity":"Quantity : " +data[j].medicineQuantity
    }
    ]
}

var medicineList = [];
for(j=0; j<data.length; j++){
    medicineList.push({
        "medicineId" : "Id : " + data[j].medicineId,
        "medicineName" : "Name : " + data[j].medicineName,
        "medicinePotency" : "Potency : "+ data[j].medicinePotency,
        "medicinePrice" :"Price : " +data[j].medicinePrice,
        "medicineQuantity":"Quantity : " +data[j].medicineQuantity
    });            
}
$scope.medicineList = medicineList;

问题 - 您为每次迭代设置了$scope.medicineList,因为它始终会使用上一条记录进行更新。