0

I am making a json array of the objects getting from the database by using angularjs, but only the last record is showing else is not showing.

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
            }
            ]
        }
    });
}
}]);

Can anybody tell me the mistake that i m making, I shal be thankful :)

2 Answers 2

1

Update from

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
    }
    ]
}

to

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;

Problem - you were setting $scope.medicineList for every iteration because of which it was always getting updated with last record.

Sign up to request clarification or add additional context in comments.

Comments

0

@nikhil answer is good and it works, but there's a couple of points worth noting.

  1. The $http legacy promise methods success and error have been deprecated. Use the standard then method instead:

    $http({
      method: 'GET',
      url: '/yourUrl'
    }).then(
    function successCallback(response) 
    {
       // Things went ok
    }, 
    function errorCallback(response) 
    {
       // Things went bad
    });
    
  2. The data you are receiving could already be in the JSON format you expect, so you only have to bind it to the scope, like:

    $scope.medicineList = data;
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.