-1

I want to give a post request using my API. The JSON is like this:

{
    "_id": "56b8e96xxxxxxxxxx7cd",
    "name": "abc",
    "conditions": [
      {
        "name": "Condition 1"
      },
      {
        "name": "Condition 2"
      }
    ],
    "id": 10
}

The following is the angular code:

app.factory('Cohort', function($resource) {
    return $resource('http://API URL:id') 
});

I am using the following angular function to give the post request:

$scope.createCohort= function (){
    var arr=["condition 1","condition 2"];
    var cohort=new Cohort();
    cohort.name=$scope.CohortName;
    cohort.id=$scope.CohortId;
    for(var i=0;i<length_of_arr;i++)
    {      
       cohort.conditions[i].name=arr[i]  // This line gives me error.
    }

    Cohort.save(cohort,function(){     
    });
};

The error is

Cannot read property '0' of undefined

How can I give the post request to it ?

Shubham Pendharkar
  • 310
  • 1
  • 4
  • 17
  • take a look here: http://stackoverflow.com/questions/19490560/angularjs-resource-promise, when dealing with async functions ($recourse) you need to use callback functions. – Peter Feb 09 '16 at 10:10

1 Answers1

1

Since you don't precise where you declare you var arr=[..]. I presume you have declare it inside a function and not in your controller which make it invisble to the createCohort function.

Either declare a var arr=[] in your controller (not in a function define in it) and remove the var on the place you set the value (so you don't mask it). Or use $scope.arr = [...];

Note that if you never use arr in your view template it's better to not store it in the $scope because angular watch evrery change of all fields in the $scope.

EDIT :

here is the problem: before the for loop add :

cohort.conditions = [];

and in the for loop do :

cohort.conditions.push({name:arr[i]});
Walfrat
  • 5,363
  • 1
  • 16
  • 35