This happens because $http
executes an asynchronous request, so resultado
at the moment you loga has not been populated yet. It will only be populated once the request ends and in your case if it is successful. By the way you should create a service to do this and not within control, but that is another story.
For you to use this data, wherever you are using it, you have to continue within success
. For example: If you use this in a third-party lib, you have to call it in there, or in any function, passing that result.
Is it clear?
Update
In your case, to include a service you can use factory
or service
, both providers . This example uses the first one:
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 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 the full service scope, which in turn returns a deferred
. Note also that the controller now no longer works with the callback success
but with then
, which is called promisses . The success
and error
are in the service to be dealt with there. But the idea is the same, you have to continue your flow from the callback then
.
Update 2
A better way to parse into this xml might look 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 you have a cross-browser version (the above code is probably will not work in IE). And in this post can do in jQuery, which is much simpler.