Given the following Angular 1.5 Component Controller...
'use strict'
function MyController($http){
//The template variable for cloning on a form
this.myVarTemplate = {};
//The Data I wish to send to the server
this.myVarTemplate.data = {};
//Other form specific / callback data
this.myVarTemplate.meta = {};
this.myVarArray = [];
//A container of raw data I'm parsing for example, on whitespace bound to a text input
this.rawInput = '';
this.parse = function(){
var temp = this.rawInput.split(' ');
for( var i = 0; i < temp.length; i++){
var container = angular.copy(this.myVarTemplate);
container.data = temp[i];
this.myVarArray.push(container);
}
}
this.upload = function(){
for(var i = 0; i < this.myVarArray.length; i++){
$http({
method: 'POST',
url: <url here>,
data: this.myVarArray[i]
}).then(function(response){
//My Success callback won't work!!!!
//Response logs successfully, data is retrieved
console.log(response);
//this.myVarArray.meta is undefined??
//console.log(this.myVarArray) is undefined
this.myVarArray[i].meta.reply = response.data;
}, function(message){
//Never been an issue here
alert('Something Bad happened? doesn't happen');
}).finally(function(){
//Works
this.myVarArray[i].meta.wasSent = true;
});
}
}
})
I am trying to return a batch of AJAX query results to their proper corresponding form objects. It seems as though this.myVarArray is undefined within the context of the $http service success callback. Why is this? Is this a quirk of Angular or of Javascript itself? I understand that the $http service returns a promise, but that should be resolved within the context of the callback. Why is myVarArray undefined?
Many thanks in advance for any insight.
Edited: Fixed my example code... :)
this.myVarArray is an array of string based on what has been split from raw input in your parse. You are trying to assign an object property (.meta) to a string array element. You could try something along the lines of:
this.myVarObjArray;
this.rawInput = '';
this.parse = function(){
var temp = this.rawInput.split(' ');
var valArray = []
for( var i = 0; i < temp.length; i++){
valArray.push(angular.copy(temp[i]));
this.myVarObjArray[i] = { val: valArray};
}
}
this.upload = function(){
angular.forEach(this.myVarObjArray, function(obj,v){
$http({
method: 'POST',
url: <url here>,
data: obj.val
}).then(function(response){
//My Success callback won't work!!!!
//Response logs successfully, data is retrieved
console.log(response);
//this.myVarArray.meta is undefined??
//console.log(this.myVarArray) is undefined
obj.meta = {reply :response.data};
....
})
Essentially your trying to assign an object property to a string array element. This won't work. My syntax might not be 100%. If you pull into a plunker i'll get a working example for you. This should get you on the right track.