I have an array called agenciasUri
, which formats the data before inserting it into it. After that, I set the JSON jsonObj
to send a request. What I find strange is that it's working properly.
Why can I access agenciasUri
? How does visibility of a variable within a JavaScript loop (life cycle) work?
$scope.salvar = function () {
var agenciasSeparadas = $scope.opcoes + '';
agenciasSeparadas = agenciasSeparadas.split(',');
try {
var agenciasUri = [];
for (var i = 0; i < $scope.listaAgencias.length; i++) {
var json = $scope.listaAgencias[i];
for (var k = 0; k < agenciasSeparadas.length; k++) {
if (json.nome == agenciasSeparadas[k]) {
agenciasUri.push(json._links.self.href);
}
}
}
} catch (err) {
alert(err);
}
var jsonObj = {
nome: $scope.nome,
tipo: $scope.tipo,
agencias: agenciasUri
};
alert(JSON.stringify(jsonObj));
veiculosAPI.postVeiculo(jsonObj)
.success(function (data, status, headers, config) {
$scope.nome = null;
$scope.tipo = null;
}).error(function (data, status, headers) {
alert("Erro ao salvar dados do veiculo!");
alert(data + "\t" + JSON.stringify(data));
});
};