This happens because the $http
executes an asynchronous request, then the resultado
the moment you loga it has not been filled in yet. It will only be filled in after the request is finished and in your case if it is successful. Incidentally you should create a service to do this and not within the control, but this is another story.
To use this data, wherever you are using it, you have to continue within the success
. For example: If you use this in a third-party lib, you have to call it in, or in any function, passing this result.
It was clear?
Updating
In your case, to include a service you can use the factory
or service
, both providers. This example uses the first:
app.factory('controllerPrincipalService', function($http, $q) {
return {
getResultado: function(id)
{
var deferred = $q.defer();
$http(
{
method: 'GET',
url: 'url',
data: {id:id}
}).success(function(data, status, headers, config)
{
deferred.resolve(data);
}).error(function(data, status, headers, config)
{
deferred.reject(status);
});
return deferred.promise;
}
};
});
So you separate the layers and leave the requests outside the controller, which makes your code much more organized. Your controller would look like this:
app.controller('controllerPrincipal', ["$scope", "controllerPrincipalService", function($scope, $http) {
controllerPrincipalService.getResultado(id).then(function(dados)
{
// limpando o retorno
var p = data.search("{")-1;
var res = data.substring(76);
var f = res.search('<');
dados = data.substring(p, p+f);
resultado = JSON.parse(dados);
});
}]);
Note the dependency injection that the controller has ["$scope", "controllerPrincipalService"
. This gives you in the scope the full service, which in turn returns a deferred
. Also note that the controller no longer works with callback success
but rather with the then
, what is called precepts. The success
and the error
stay in service to be treated there. But the idea is the same, you have to continue your flow from the callback then
.
Update 2
A better way to parse in this xml can be like this:
xmlparser = new DOMParser();
xmlDoc = xmlparser.parseFromString(dados, "text/xml");
var string = xmlDoc.getElementsByTagName("string")[0].innerHTML;
var json = JSON.parse(string);
In this article has a cross-browser version (the above code probably won’t work in IE). And in this post has how to do in jQuery, which is much simpler.
Fluorescent or incandescent light?
– noNihongo
The one that works kkkk
– LucasMoura
Got confused try to explain better
– Silvio Andorinha
within $http, I store the date in the result variable, as access to the external result variable, outside of $http
– LucasMoura