I am in need of sending the following batch data to the database, but I am facing difficulties in including the course_id along with the batchData. Currently, I am retrieving the course_id from another service that fetches data from a course table. I am unable to access response.data.data[0]._id outside the function as it is a local variable. Is there any way to bind the course_id with batchData object?
app.controller('batch_add', function($scope, $http) {
$http.get("/courses/getall")
.then(function(response) {
if (response.data.length == 0) {
$scope.items = [{ course_name: "No data", course_desc: "No data", course_fees: "No data" }];
} else {
$scope.items = response.data.data;
var course_name_items = []
for (var i = 0; i < $scope.items.length; i++) {
course_name_items.push($scope.items[i].course_name)
}
$scope.course_items = course_name_items;
}
});
$scope.batch_status_items = ['Pending', 'Running', 'Finished', 'Canceled' ]
$scope.batchData={};
$scope.login = {"batchData" : $scope.batchData};
$scope.submitForm = function() {
$scope.login = {"batchData" : $scope.batchData};
$scope.fail = false;
$http({
method : 'POST',
url: 'batches/add',
data : $scope.login
})
.success(function(data) {
if (data.success == true) {
$scope.fail = true;
$scope.success = true;
$scope.success_message = data.message;
var courseName = $scope.batchData.course_name;
$http.get("/courses/search/"+courseName)
.then(function(response) {
if (response.data.length == 0) {
console.log("error");
} else {
$scope.batchData.course_id= response.data.data[0]._id
}
});
toastr.options = {"positionClass": "toast-bottom-right"}
Command: toastr["success"]("A new batch has been added!")
} else {
$scope.fail = true;
$scope.success = false;
$scope.error_message = data.message;
console.log($scope.success_message);
// toastr.error('Something went wrong.', 'Ooops!')
}
});
$scope.batchData.course_id = response.data.data[0]._id
};
});