2015-12-19 92 views
0

我正在通過使用angularjs從數據庫中獲取對象的json數組,但只有最後一條記錄顯示else沒有顯示。如何從數據庫記錄中創建json數組

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

更新從

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它總是隨着最後一個記錄而更新。

+1

感謝它的工作:) – Asad

+0

@Asad - 感覺很好,以幫助你 – nikhil

0

@nikhil答案很好,它的工作原理,但有幾點值得注意。

  1. $http遺留承諾方法successerror已棄用。使用標準then方法代替:

    $http({ 
        method: 'GET', 
        url: '/yourUrl' 
    }).then(
    function successCallback(response) 
    { 
        // Things went ok 
    }, 
    function errorCallback(response) 
    { 
        // Things went bad 
    }); 
    
  2. 您收到可能已經在你所期望的JSON格式,所以您只需將其綁定到的範圍,就像數據:

    $scope.medicineList = data;